首页 > 代码库 > BCD与ASCII码互转-C语言实现

BCD与ASCII码互转-C语言实现

最近由于项目需要,需要将BCD编码转换为对应的字符串,下面为C语言实现,经测试好用!

     转载请标明出处!

/*BCD 与 ASCII码转换*/

/*******************************************************************
函数名:  asc2bcd 
功能描述:将ascii码转换为bcd码
参数:    
         bcd:转换后的BCD码
         asc:需转换的ASCII码串
         len:需转换的ascii码串长度

返回值:  uint32 
                              0:成功
                              其他:失败
********************************************************************/
uint32 asc2bcd(uint8* bcd, const uint8* asc, uint32 len);

/*******************************************************************
函数名: bcd2asc 
功能描述:将bcd码转换为ascii码串
参数:    
         asc:转换的ASCII码串
         bcd:需转换的BCD码
         len:需转换的BCD码长度

返回值:  uint32 
                              0:成功
                              其他:失败
********************************************************************/
uint32 bcd2asc(uint8* asc, const uint8* bcd, uint32 len);

    
#include <assert.h>

#include "utils.h"
//基于查表实现BCD与Ascii之间的转换
static uint8 bcd2ascii[16] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

static uint8 ascii2bcd1[10] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9};
static uint8 ascii2bcd2[6]  = {0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F};

uint32 
ASC2BCD(uint8 *bcd, const uint8 *asc, uint32 len)
{
    uint8 c = 0;
    uint8 index = 0;
    uint8 i = 0;  
    
    len >>= 1;    

    for(; i < len; i++) {
        //first BCD
        if(*asc >= 'A' && *asc <= 'F') {
            index = *asc - 'A'; 
            c  = ascii2bcd2[index] << 4;
        } else if(*asc >= '0' && *asc <= '9') {
            index = *asc - '0';
            c  = ascii2bcd1[index] << 4;
        }
        asc++;

        //second BCD
        if(*asc >= 'A' && *asc <= 'F') {
            index = *asc - 'A'; 
            c  |= ascii2bcd2[index];
        } else if(*asc >= '0' && *asc <= '9') {
            index = *asc - '0';
            c  |= ascii2bcd1[index];
        }
        asc++;

        *bcd++ = c;
    }   

    return 0;
}

uint32
BCD2ASC (uint8 *asc, const uint8 *bcd, uint32 len)
{
    uint8 c = 0;
    uint8 i;


    for(i = 0; i < len; i++) {
        //first BCD
        c = *bcd >> 4;
        *asc++ = bcd2ascii[c];


        //second
        c = *bcd & 0x0f;
        *asc++ = bcd2ascii[c];
        bcd++;
    }


    return 0;
}

int main(void)//测试程序
{
    const unsigned char ascii[12] = {'1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C'};
    unsigned char bcd[6];

    ASC2BCD(bcd, ascii, 12, 0); 
    
    int i = 0;

    printf("ascii = %s\n", ascii);

    for(; i < 6; i++) {
        printf("bcd = 0x%.2x\n", bcd[i]);
    }   

    /*  
       unsigned char ascii[13] = {0};
       const unsigned char bcd[6] = {0x01, 0x23, 0x45, 0xCD, 0xEF, 0xAB};

       BCD2ASC(ascii, bcd, 6, 0);
       printf("ascii = %s\n", ascii);
       */
    return 0;
}

   

BCD与ASCII码互转-C语言实现