Decimal to Binary Coded Decimal (BCD) Conversion in C or C++

In this tutorial we will see how to convert the decimal number to a BCD and BCD to a decimal number.

What is a Binary Coded Decimal (BCD) ?

Binary coded decimal is number where each decimal is stored individually. It will confuse much so we can see a example.
Let us take 52 as a decimal number, the equivalent BCD number is 82.

How ?

We need to take each digit individually 
5 -> 0101
2 -> 0010

So that 0101 0010 represent 82 as a decimal number.

How to implement it in a C or C++ program

We shall take the same example, In this 52 we need to split those two digits. It can be done by dividing(1) by 10 and Mod (%) by 10. Divide(/) by 10 will give first digit and Mod (%) by 10 will give the second digit. After getting the first digit Left shift it by 4 will move it 4 bits forward and by logical Or(|) the second digit will give the result.

Decimal to BCD Conversion Program 

int  DecimalToBCD (int Decimal)
   return (((Decimal/10) << 4) | (Decimal % 10));

BCD to Decimal Conversion Program

int BCDToDecimal(int BCD)
   return (((BCD>>4)*10) + (BCD & 0xF))

Note: This example will work only with two digit variables if the decimal number is more than that 100 or 1000 should be used based on the decimal value. I am leaving it to yourself. Have any doubts comment below.

What is BCD ? and where it is used ?