菜鸟笔记
提升您的技术认知

bcd与ascii码互转-ag真人游戏

最近由于项目需要,需要将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 
#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;
}

 

网站地图