C中的ASCII到TBCD转换

D J*_*D J 5 c ascii tbcd

我希望在C中转换ASCII stringTBCD(Telephony Binary-Coded Decimal)格式,反之亦然.我在许多网站上搜索但找不到我的答案.

kmk*_*lan 5

最简单的可能是使用一对数组将每个ASCII字符映射到TBCD对应物.反之亦然.

根据我在维基百科上阅读的内容,您应该使用以下内容:

const char *tbcd_to_ascii = "0123456789*#abc";
const char ascii_to_tbcd[] = {
 15, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, /* filler when there is an odd number of digits */
  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 */
};
Run Code Online (Sandbox Code Playgroud)

如果您有TBCD,要将其转换为ASCII,您可以:

/* The TBCD to convert */
int tbcd[] = { 0x10, 0x32, 0x54, 0x76, 0x98, 0xba, 0xdc, 0xfe };
/* The converted ASCII string will be stored here. Make sure to have
   enough room for the result and a terminating 0 */
char ascii[16] = { 0 };
/* Convert the TBCD to ASCII */
int i;
for (i = 0; i < sizeof(tbcd)/sizeof(*tbcd); i++) {
    ascii[2 * i] = tbcd_to_ascii[tbcd[i] & 0x0f];
    ascii[2 * i + 1] = tbcd_to_ascii[(tbcd[i] & 0xf0) >> 4];
}
Run Code Online (Sandbox Code Playgroud)

要从ASCII转换为TBCD:

/* ASCII number */
const char *ascii = "0123456789*#abc";
/* The converted TBCD number will be stored here. Make sure to have enough room for the result */
int tbcd[8];
int i;
int len = strlen(ascii);
for (i = 0; i < len; i += 2)
    tbcd[i / 2] = ascii_to_tbcd[ascii[i]]
        | (ascii_to_tbcd[ascii[i + 1]] << 4);
Run Code Online (Sandbox Code Playgroud)

编辑:@Kevin指出TBCD包2个每字节的数字.