最简单的可能是使用一对数组来映射每个ASCII字符到它的TBCD对应物。反之亦然。
const char *tbcd_to_ascii = "*#abc";
const char ascii_to_tbcd[] = {
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0,11, 0, 0, 0, 0, 0, 0,10, 0, 0, 0, 0, 0, /* # * */
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 0, 0, 0, 0 /* digits */
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
0,12,13,14 /* a b c */
};
如果你有TBCD,将其转换为ASCII你会怎么做:
/* The TBCD to convert */
int tbcd[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 };
/* The converted ASCII string will be stored here. Make sure to have enough room for the result */
char ascii[16];
/* Convert the TBCD to ASCII */
int i;
for (i = 0; i < sizeof(tbcd)/sizeof(*tbcd); i++)
ascii[i] = tbcd_to_ascii[tbcd[i]];
/* For safety, null terminate the ASCII string */
ascii[i] = 0;
从ASCII到TBCD转换非常相似:
for (i = 0; ascii[i]; i++)
tbcd[i] = ascii_to_tbcd[ascii[i]];