关于BCD码,本文不做解释。本文只介绍8421 BCD码与10进制的转换。
1、8421 BCD转10进制
unsigned char bcd_to_hex(unsigned char data){ unsigned char temp; temp = ((data>>4)*10 + (data&0x0f)); return temp;}
2、10进制转8421 BCD码
unsigned char hex_to_bcd(unsigned char data){ unsigned char temp; temp = (((data/10)<<4) + (data%10)); return temp;}
测试代码:
#include <stdio.h>unsigned char bcd_to_hex(unsigned char data){ unsigned char temp; temp = ((data>>4)*10 + (data&0x0f)); return temp;}unsigned char hex_to_bcd(unsigned char data){ unsigned char temp; temp = (((data/10)<<4) + (data%10)); return temp;}int main(){unsigned char bcd = 99 , decimal = 63 ,tmp =0; tmp = bcd_to_hex(bcd);printf(“10进制值为:%d\n”,tmp);tmp = hex_to_bcd(decimal);printf(“BCD码的值为:%d\n”,tmp); return 0;}
运行结果:
10进制值为:63
BCD码的值为:99