2

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!

Ammar
  • 1,203
  • 5
  • 27
  • 64

1 Answers1

4

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.

hobbs
  • 223,387
  • 19
  • 210
  • 288