十六进制与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;
}

执行结果: