Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASCII to TBCD Conversion in C

Tags:

c

ascii

tbcd

I want to convert ASCII string to TBCD(Telephony Binary-Coded Decimal) format and vice versa in C. I searched over many sites but could not find my answer.

like image 340
Ravi Avatar asked Jan 03 '13 06:01

Ravi


2 Answers

The easiest is probably to use a pair of arrays to map each ASCII character to its TBCD counterpart. And vice versa.

From what I read on Wikipedia you should use the following:

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

If you have a TBCD, to convert it to ASCII you would do:

/* 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];
}

To convert from ASCII to 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);

Edit: @Kevin pointed out that TBCD packs two digits per byte.

like image 62
kmkaplan Avatar answered Oct 17 '22 14:10

kmkaplan


#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;
}
like image 38
perreal Avatar answered Oct 17 '22 15:10

perreal