在做嵌入式软件的设计中,常常会遇到十六进制、BCD码与十进制之间的转换,近期做M1卡的应用中,涉及了大量的十六进制、BCD码与十进制之间的转换。通过对BCD码、十六进制 权的理解,轻松的实现了他们之间的互换。
- #include <stdio.h>
- #include <string.h>
- int convert(unsigned char *dst, const unsigned char *src, int length)
- {
- int i;
- for(i=0; i<length; i++)
- {
- dst[i] = src[i]^0xFF;
- }
- return 0;
- }
- unsigned long HextoDec(const unsigned char *hex, int length)
- {
- int i;
- unsigned long rslt = 0;
- for(i=0; i<length; i++)
- {
- rslt += (unsigned long)(hex[i])<<(8*(length-1-i));
-
- }
- return rslt;
- }
- int DectoHex(int dec, unsigned char *hex, int length)
- {
- int i;
- for(i=length-1; i>=0; i--)
- {
- hex[i] = (dec%256)&0xFF;
- dec /= 256;
- }
- return 0;
- }
- unsigned long power(int base, int times)
- {
- int i;
- unsigned long rslt = 1;
- for(i=0; i<times; i++)
- rslt *= base;
- return rslt;
- }
- unsigned long BCDtoDec(const unsigned char *bcd, int length)
- {
- int i, tmp;
- unsigned long dec = 0;
- for(i=0; i<length; i++)
- {
- tmp = ((bcd[i]>>4)&0x0F)*10 + (bcd[i]&0x0F);
- dec += tmp * power(100, length-1-i);
- }
- return dec;
- }
- int DectoBCD(int Dec, unsigned char *Bcd, int length)
- {
- int i;
- int temp;
- for(i=length-1; i>=0; i--)
- {
- temp = Dec%100;
- Bcd[i] = ((temp/10)<<4) + ((temp%10) & 0x0F);
- Dec /= 100;
- }
- return 0;
- }
- int main()
- {
- register int i;
- unsigned char tmp_bff[12] = "";
-
- unsigned char HEX[4] = {0x34, 0xFE, 0x3E, 0xFF};
- unsigned long dec_hex = 0;
- dec_hex = HextoDec(HEX, 4);
-
- printf("dec_hex = %d/n", dec_hex);
-
- DectoHex(dec_hex, tmp_bff, 4);
- for(i=0; i<5; i++)
- {
- printf("tmp_bff[%d] = 0x%02X/n",i, tmp_bff[i]);
- }
-
- unsigned long dec_bcd = 0;
- unsigned char BCD[4] = {0x98, 0x23, 0x45, 0x78};
- dec_bcd = BCDtoDec(BCD, 4);
- printf("dec_bcd = %d/n", dec_bcd);
-
- DectoBCD(dec_bcd, tmp_bff, 4);
- for(i=0; i<5; i++)
- {
- printf("tmp_bff[%d] = 0x%02X/n", i, tmp_bff[i]);
- }
- getchar();
- }
假设有其它的方法能够一起讨论