How to convert decimal back BCD?

我只是一个虾纸丫 提交于 2019-12-10 10:55:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!