c语言bcd to ascii,C中的ASCII到TBCD转换

kmkaplan..

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 */

};

如果您有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包2个每字节的数字.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值