C语言中的ASCII到TBCD转换

5

我想在C语言中将ASCII字符串转换为TBCD(电话二进制编码十进制)格式,反之亦然。我在许多网站上搜索了很久,但没有找到答案。

2个回答

6
最简单的方法可能是使用一对数组将每个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 */
};

如果您有一个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];
}

将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);

编辑:@Kevin 指出 TBCD 将两个数字打包在每个字节中。

BCD的C语言实现在这里给出:http://en.wikipedia.org/wiki/Double_dabble - Bug Killer
假设我有一个以TBCD格式表示的IMSI需要转换为ASCII码。如何使用上述数组来帮助? - Ravi
@DJ 我其实不知道IMSI是什么,但我编辑了我的答案,以示例说明如何将TBCD数组转换为ASCII字符串。 - kmkaplan
@kmkaplan,你的回答真的帮了我很多。谢谢 :) IMSI是附加在我们手机SIM卡上的国际移动用户标识。 - Ravi
1
TBCD将两个数字放入一个字节中。除非我漏掉了什么,否则这个答案并没有做到这一点,是错误的。 - Kevin
@Kevin 感谢你指出这个问题,我已经相应地修复了代码。但是还没有测试过 ;-) - kmkaplan

3
#include <ctype.h>
int cnv_tbcd(char *str, char *tbcd) {
  int c = 0;
  int err = 0;
  for (c=0; str[c]; c++) {
    if (isdigit(str[c])) {
      tbcd[c] = str[c] & 0x0f;
    } else {
      switch(str[c]) {
        case '*': tbcd[c]  = 0x0a; break;
        case '#': tbcd[c]  = 0x0b; break;
        case 'a': tbcd[c]  = 0x0c; break;
        case 'b': tbcd[c]  = 0x0d; break;
        case 'c': tbcd[c]  = 0x0e; break;
        default:  tbcd[c] = 0xff; err++;
      }   
    }   
  }
  if (c % 2 == 0) {
    tbcd[c]   = 0x0f;
    tbcd[c+1] = 0;
  }
  return err;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接