十六进制与ascii码互转 C语言实现

十六进制与ascii码互转 C语言实现

1. ascii转16进制

/**
 * func  : char_to_hex()
 * desc  : convert ascii to 16 hex
 * input : ascii
 * return: hex
 */
unsigned char char_to_hex(unsigned char chr)
{
    if((chr>='0')&&(chr<='9'))
        chr = 0x30+(chr-'0');
    else if((chr>='A')&&(chr<='Z'))//capital
        chr = 0x41+(chr - 'A');
    else if((chr>='a')&&(chr<='z'))//little
        chr = 0x61+(chr-'a');
    else
        chr = 0xff;
    return chr;
}

2.  16进制转ascii

/**
 * func  :hex_to_char() 
 * desc  :transform hex to ascii 
 * input :hex 
 * return:ascii
 */
unsigned char hex_to_char(unsigned char hex)
{
    if((hex>=0x30)&&(hex<=0x39))
        hex = '0' + hex-0x30;
    else if((hex>=0x41)&&(hex<=0x5A)) // capital
        hex = 'A' + (hex - 0x41);
    else if((hex>=0x61)&&(hex<=0x7A)) // little case
        hex = 'a' + (hex - 0x61);
    else 
        hex = 0xff;
    return hex;
}

3. 验证

int main(void)
{
#if 0
    unsigned char chr = 'x';
    unsigned char hex = 0x45;
    unsigned char buff = 0xff;

    buff = hex_to_char(hex);
    printf("hex_to_char:%c\n", buff);
    
    buff = char_to_hex(chr);
    printf("0x%02x\n",buff);
#else
    unsigned char str[] = "hello";
    unsigned char hex[4] = {0x61,0x62,0x41,0x42};
    unsigned char buff[32] = {0};
    int i,len;

    len = strlen(str);
    for(i = 0; i < len; i++)
        buff[i] =char_to_hex(str[i]);
    for(i = 0;i < len; i++)
        printf("char_to_hex:0x%02x\n",buff[i]);

    for(i = 0; i < 4; i++) 
        buff[i] = hex_to_char(hex[i]);
    buff[4] = '\0';
    printf("hex_to_char:%s\n",buff);
#endif
    return 0;
}

执行结果:

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值