[原创] 单片机C语言的十六进制(HEX)转BCD码程序

tiankai001   2018-3-23 11:05 楼主
此内容由EEWORLD论坛网友tiankai001原创,如需转载或用于商业用途需征得作者同意并注明出处 说明:本程序分别列举了单字节HEX码转换为BCD型数据;2字节HEX码转换为BCD型数据;4字节HEX码转换为BCD型数据的的方法。
  1. void HEXtoBCDData(void)
  2. {
  3. unsigned char ucHEXdata[10] = {0},ucBCDdata[10] = {0};
  4. unsigned int uiHEXdata = 0;
  5. unsigned long int ulHEXdata = 0;
  6. //[color=#00ff][size=4]单字节HEX码转换为BCD型数据[/size][/color]
  7. ucHEXdata[0] = 0x63; //十进制为99
  8. ucBCDdata[0] = (ucHEXdata[0]/10)*0x10 + (ucHEXdata[0]%10);
  9. //ucBCDdata[0]=99
  10. ucHEXdata[0] = 0xf5; //十进制为245
  11. ucHEXdata[1] = ucHEXdata[0]/100;
  12. ucHEXdata[2] = ucHEXdata[0]%100;
  13. ucBCDdata[0] = ucHEXdata[1];
  14. ucBCDdata[1] = (ucHEXdata[2]/10)*0x10 + (ucHEXdata[2]%10);
  15. //ucBCDdata[1]=2,ucBCDdata[0]=45
  16. //[color=#00ff][size=4]2字节HEX码转换为BCD型数据[/size][/color]
  17. uiHEXdata = 0xfff5; //十进制为65525
  18. ucHEXdata[1] = uiHEXdata%100;
  19. ucBCDdata[0] = (ucHEXdata[1]/10)*0x10 + (ucHEXdata[1]%10);
  20. uiHEXdata = uiHEXdata/100;
  21. ucHEXdata[2] = uiHEXdata%100;
  22. ucBCDdata[1] = (ucHEXdata[2]/10)*0x10 + (ucHEXdata[2]%10);
  23. uiHEXdata = uiHEXdata/100;
  24. ucHEXdata[3] = uiHEXdata%100;
  25. ucBCDdata[2] = (ucHEXdata[3]/10)*0x10 + (ucHEXdata[3]%10);
  26. //ucBCDdata[2]=6,ucBCDdata[1]=55,ucBCDdata[0]=25
  27. //[color=#00ff][size=4]4字节HEX码转换为BCD型数据[/size][/color]
  28. ulHEXdata = 0xfffffff5; //十进制为4294967285
  29. ucHEXdata[1] = ulHEXdata%100;
  30. ucBCDdata[0] = (ucHEXdata[1]/10)*0x10 + (ucHEXdata[1]%10);
  31. ulHEXdata = ulHEXdata/100;
  32. ucHEXdata[2] = ulHEXdata%100;
  33. ucBCDdata[1] = (ucHEXdata[2]/10)*0x10 + (ucHEXdata[2]%10);
  34. ulHEXdata = ulHEXdata/100;
  35. ucHEXdata[3] = ulHEXdata%100;
  36. ucBCDdata[2] = (ucHEXdata[3]/10)*0x10 + (ucHEXdata[3]%10);
  37. ulHEXdata = ulHEXdata/100;
  38. ucHEXdata[4] = ulHEXdata%100;
  39. ucBCDdata[3] = (ucHEXdata[4]/10)*0x10 + (ucHEXdata[4]%10);
  40. ulHEXdata = ulHEXdata/100;
  41. ucHEXdata[5] = ulHEXdata%100;
  42. ucBCDdata[4] = (ucHEXdata[5]/10)*0x10 + (ucHEXdata[5]%10);
  43. //ucBCDdata[4]=42,ucBCDdata[3]=94,
  44. //ucBCDdata[2]=96,ucBCDdata[1]=72,ucBCDdata[0]=85
  45. ulHEXdata = 0xfffffff4; //十进制为42 94 96 72 84
  46. for(int i=0;i<5;i++)
  47. {
  48. ucHEXdata[i]=ulHEXdata%100;
  49. ulHEXdata=ulHEXdata/100;
  50. ucBCDdata[i]=(ucHEXdata[i]/10)*0x10+ucHEXdata[i]%10;
  51. }
  52. //ucBCDdata[4]=42,ucBCDdata[3]=94,
  53. //ucBCDdata[2]=96,ucBCDdata[1]=72,ucBCDdata[0]=84
  54. }
本帖最后由 tiankai001 于 2018-3-23 11:08 编辑

回复评论 (3)

兄弟,不错啊,分享些有用的小程序片段,多谢了,已经拷贝,留着备用了
点赞  2018-3-23 13:01
引用: star_66666 发表于 2018-3-23 13:01
兄弟,不错啊,分享些有用的小程序片段,多谢了,已经拷贝,留着备用了

感谢支持,回头我再分享一些
点赞  2018-3-23 14:05
期待啊
点赞  2018-3-23 14:16
电子工程世界版权所有 京B2-20211791 京ICP备10001474号-1 京公网安备 11010802033920号
    写回复