EmbeddedRelated.com

Binary Coded Decimal (BCD) - ASCII Converter

Dr Cagri Tanriover February 12, 2013 Coded in C

BCD format is often used in LCDs and Real Time Clocks. It is basically hex format that works on mod 10 (if that makes sense). I recently developed and tested two small, dead simple but powerful functions:

1 - BCD to ASCII ( bcdToAscii )

2 - ASCII to BCD ( asciiToBcd )

I just wanted to share those with the community in case others need it as well. The code is fully commented to make life easier for fellow developers.

Enjoy!

char bcdToAscii( unsigned char bcdNibble )
{
  char result;
	
  if( bcdNibble < 10 )
  {// valid BCD input. ( [0,9] is the valid range for BCD input. )
    result = (char)( bcdNibble + 48 );	// +48 is applicable to [0,9] input range.
  }// end if
  else
  {// invalid input
    result = '0';
  }// end else

  return( result );
	
}// end bcdToAscii()

unsigned char asciiToBcd( char asciiByte )
{/* Converts an input ASCII character (expected within the [ '0' - '9' ] range) into its BCD counterpart. */
	
  unsigned char result;

  if( 
      asciiByte >= '0'
      && asciiByte <= '9'
  )
  {// range check passed.
    result = (unsigned char)(asciiByte - 48);	// -48 offset gives the decimal value of the ASCII character.
  }
  else
  {// range check failed.
    result = 0;
  }// end else

  return( result );
	
}// end asciiToBcd()