BCD to Decimal And Decimal to BCD

Himadri Ganguly picture Himadri Ganguly · Aug 13, 2017 · Viewed 12.6k times · Source

I am writing a library for RTC module in Arduino where the data is stored in BCD. I know how the Decimal number is converted into BCD but having some problem while writing it programmatically. After searching the internet I got two formulas which are as follows and working perfectly but cannot understand how it is calculating.

1. Formula1

DEC to BCD

(value / 10 * 16) + (value % 10)

Example

DEC -> 40 which converted to 01000000 in BCD which is again equal to 64.

So if I put into the formula I get the same result.

(40/10 * 16) + (40%10)
= (4*16) + 0
= 64

BCD to DEC

(value / 16 * 10) + (value % 16)

2. Formula2

DEC to BCD

val + 6 * (val / 10)

BCD to DEC

val - 6 * (val >> 4)

If anyone can explain it in details it will be helpful.

Thanks to all in advance.

Answer

TomServo picture TomServo · Aug 13, 2017

The correct conversion functions are:

byte bcdToDec(byte val)
{
  return( (val/16*10) + (val%16) );
}

byte decToBcd(byte val)
{
  return( (val/10*16) + (val%10) );
}

Why does this work? Let's take a single digit 5. In binary, it's

0101 = 5 

Now let's take that same digit, shift it four places to the left by adding four zeroes to the right:

0101 0000 = 50 BCD

That's how BCD works. Since it takes four binary digits to represent the decimal digits 0 through 9, each single decimal digit is represented by four bits. The key is that shifting four places in binary multiplies or divides by 16, so that's the reason for the 16 values in the formulas.

So let's take 96:

0110 = 6
1001 = 9
1001 0110 = 96 BCD