Continue to Site

# BCD to decimal convertion and vice versa

Some compilers may have built in functions for these convertions, but others don't. Below are two functions for converting a BCD number to decimal and vice versa:

Code C - [expand]1
2
3
4
5
6
7
8
9
10
11
#define uint8 unsigned char

uint8 BCDToDecimal (uint8 bcdByte)
{
return (((bcdByte & 0xF0) >> 4) * 10) + (bcdByte & 0x0F);
}

uint8 DecimalToBCD (uint8 decimalByte)
{
return (((decimalByte / 10) << 4) | (decimalByte % 10));
}

And a brief calling example:

Code C - [expand]1
2
3
4
5
uint8 decNum = 52;
uint8 bcdNum = 0x39;

uint8 convertedToBCD = DecimalToBCD(decNum);  //convertedToBCD = 0x52
uint8 convertedToDec = BCDToDecimal(bcdNum);  //convertedToDec = 39

I am waiting feedback for better or more effective converting ways.

Cheers!

Nice information
how can i get the ASCII value ?
convertedToDec + 0x30h;
right ?

sir have you ?
how can i convert bcd (read from adc ) to ASCI value ?

thannara123 said:
how can i get the ASCII value ?
convertedToDec + 0x30h;
Hi thannara123.

Sorry for the late reply. Although I am subscribed to this blog entry, I didn't get any notification. :sad:

Anyway, you are right if we are talking about one digit only (even though I prefer OR compared to addition). For more digits, you must split the number to its digits and then convert them in separate.
For example if you have decimal number 38, then you will split it to 3 and 8 and then OR those values with 0x30. The final result will be 0x33 and 0x38 ('3' and '8').

Alexandros

Author
alexxx