开发者

BYTE BCD to ASCII conversion optimization

I've written a function in c that converts a byte (unsigned char) BCD string into ASCII. Please have look at the code and advice some improvements.

Is there any other efficient way that can convert BYTE BCD to ASCII.

BYTE_BCD_to_ASC(BYTE *SrcString, char *DesString)
{

        switch (((BCD *)S开发者_高级运维rcString)->l)
        {
            case 10:/*A*/
            case 11:/*B*/
            case 12:/*C*/
            case 13:/*D*/
            case 14:/*E*/
            case 15:/*F*/
                *DesString = (char)(((BCD *)SrcString)->l + '0' + 7);
                break;
            default:
                *DesString = (char)(((BCD *)SrcString)->l + '0');
                break;
        }

        switch (((BCD *)SrcString)->h)
        {
            case 10:
            case 11:
            case 12:
            case 13:
            case 14:
            case 15:
                *(DesString + 1) = (char)(((BCD *)SrcString)->h + '0' + 7);
                break;
            default:
                *(DesString + 1) = (char)(((BCD *)SrcString)->h + '0');
                break;
        }
    *(DesString + 2) = '\0';
}

thanks

Fakhar


I think I'd do something like this:

void BCD2ASC(unsigned char src, char *dest) { 
    static const char outputs[] = "0123456789ABCDEF";
    *dest++ = outputs[src>>4];
    *dest++ = outputs[src&0xf];
    *dest = '\0';
}


Try this:

void BCD_To_ASCII(unsigned char bcd_value, char * p_ascii_text)
{
  //--------------------------------------------------
  // BCD contains digits 0 .. 9 in the binary nibbles
  //--------------------------------------------------
  *p_ascii_text++ = (bcd_value >> 4)  + '0';
  *p_ascii_text++ = (bcd_value & 0x0f) + '0';
  *p_ascii_text = '\0';
  return;
}


finally I have implemented the routine as follows

static const char s_szHexAscNo[] = "0123456789ABCDEF";

void BYTE_BCD_to_ASC(BYTE *SrcString, char DesString[3], int BCDflag)
{
    assert(SrcString != NULL);
    assert(DesString != NULL);

    if ( BCDFlag_Normal == BCDflag)
    {
        *DesString++ = (char) s_szHexAscNo[((BCD *)SrcString)->l];
        *DesString++ = (char) s_szHexAscNo[((BCD *)SrcString)->h];
    }

    if (BCDFlag_Reverse == BCDflag)
    {
        *DesString++ = (char) s_szHexAscNo[((BCD_REVERSE *)SrcString)->l];
        *DesString++ = (char) s_szHexAscNo[((BCD_REVERSE *)SrcString)->h];
    }
    *DesString = '\0';
}

/* BCD and BCD_REVERSE  are defined as */

typedef struct
{
unsigned char    l : 4;
unsigned char    h : 4;
} BCD;

typedef struct
{
unsigned char    h : 4;
unsigned char    l : 4;
} BCD_REVERSE;

comments would be appreciated....

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜