问题
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!
回答1:
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.
来源:https://stackoverflow.com/questions/28139264/how-to-convert-decimal-back-bcd