基于查表实现BCD与Ascii之间的转换
//基于查表实现BCD与Ascii之间的转换
static char unsigned bcd2ascii[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
static char unsigned ascii2bcd1[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
static char unsigned ascii2bcd2[6] = {0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};
int ASC2BCD(unsigned char *bcd, const unsigned char *asc, int len)
{
unsigned char c = 0;
unsigned char index = 0;
unsigned char i = 0;
len >>= 1;
for(; i < len; i++) {
//first BCD
if(*asc >= 'A' && *asc <= 'F') {
index = *asc - 'A';
c = ascii2bcd2[index] << 4;
} else if(*asc >= '0' && *asc <= '9') {
index = *asc - '0';
c = ascii2bcd1[index] << 4;
}
asc++;
//second BCD
if(*asc >= 'A' && *asc <= 'F') {
index = *asc - 'A';
c |= ascii2bcd2[index];
} else if(*asc >= '0' && *asc <= '9') {
index = *asc - '0';
c |= ascii2bcd1[index];
}
asc++;
*bcd++ = c;
}
return 0;
}
int BCD2ASC (unsigned char *asc, const unsigned char *bcd, int len)
{
unsigned char c = 0;
unsigned char i;
for(i = 0; i < len; i++) {
//first BCD
c = *bcd >> 4;
*asc++ = bcd2ascii[c];
//second
c = *bcd & 0x0f;
*asc++ = bcd2ascii[c];
bcd++;
}
return 0;
}
int main(void)//测试程序
{
const unsigned char ascii[12] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C'};
unsigned char bcd[6];
ASC2BCD(bcd, ascii, 12, 0);
int i = 0;
rintf("ascii = %s\n", ascii);
for(; i < 6; i++) {
printf("bcd = 0x%.2x\n", bcd[i]);
}
/*
unsigned char ascii[13] = {0};
const unsigned char bcd[6] = {0x01, 0x23, 0x45, 0xCD, 0xEF, 0xAB};
BCD2ASC(ascii, bcd, 6, 0);
printf("ascii = %s\n", ascii);
*/
return 0;
}