Ammar
Ammar

Reputation: 1233

How to convert decimal to BCD?

I am able to convert BCD to decimal, for example I can convert 0x11 to 11 instead of 17 in decimal. This is the code I used.

unsigned char hex = 0x11;
unsigned char backtohex ;

int dec = ((hex & 0xF0) >> 4) * 10 + (hex & 0x0F);

Now I want to convert dec back to BCD representation. I want 11 to be converted back to 0x11 not 0x0B. I am kind of confused as how to go back.

Thanks!

Upvotes: 2

Views: 668

Answers (1)

hobbs
hobbs

Reputation: 239801

Assuming your input is always between 0 and 99, inclusive:

unsigned char hex = ((dec / 10) << 4) | (dec % 10);

Simply take the upper digit and shift it left by one nibble, and or the lower digit in place.

Upvotes: 4

Related Questions