欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C语言16进制与ASCII字符相互转换

程序员文章站 2022-06-16 20:34:58
1、把获取到的16进制数据转换成相同字符的ascii字符,例:get[2] = {0x11,0x22}; → put[4]={'1','1','2...

1、把获取到的16进制数据转换成相同字符的ascii字符,例:get[2] = {0x11,0x22};  →  put[4]={'1','1','2','2'};

数据的转换主要通过sprintf();来完成的,对于该函数网上有许多讲解,想要了解的可以查看一下。

typedef unsigned char uint8_t;
char data[64];
 
uint8_t *hex_to_ascii(uint8_t *str, uint32_t len)
{
    uint8_t *hex_buf = str;
    for (int i = 0; i < len; i++)
    {
        sprintf(&data[i * 2], "%02x", hex_buf[i]);
    }
    return (uint8_t *)data;
}

2、 把获取到的ascii字符转换成相同字符的16进制,例:get[4]={'a','a','b','b'}; →  put[2] = {0xaa,0xbb};

ascii转换成16进制主要通过sscanf();来完成的。

typedef unsigned char uint8_t;
char data[64];
uint8_t *ascii_to_hex(char *str, uint32_t len)
{
    char *str_buf = str;
    uint8_t *hex = (uint8_t *)data;
    uint8_t data_buf[len];
    for (int i = 0; i < len; i++)
    {
        sscanf(str_buf, "%02x", (int *)&data_buf[i]);
        str_buf += 2;
    }
    memcpy(hex, data_buf, len);
    return hex;
}

3、把获取到的16进制转换成对应的ascii字符,例:get[4]={'a','a','b','b'}; → put[4]={0x61,0x61,0x62,0x62};

typedef unsigned char uint8_t;
char data[64];
uint8_t *char_to_hex(char *str,uint32_t len)
{
    char *hex_buf = str;
    uint8_t *hex = (uint8_t *)data;
    for (int i = 0; i < len; i++)
    {
        if ((hex_buf[i] >= '0') && (hex_buf[i] <= '9'))        //0x30--0x39
            hex_buf[i] += 0x30;
        else if ((hex_buf[i] >= 'a') && (hex_buf[i] <= 'z'))   //0x61--0x66
            hex_buf[i] += 0x61;
        else if ((hex_buf[i] >= 'a') && (hex_buf[i] <= 'z'))   //0x41--0x46
            hex_buf[i] += 0x41;
        else
            hex_buf[i] += 0xff;
    }
    memcpy(hex, hex_buf, len);
 
    return hex;
}

4、把获取到的ascii转换成对应的16进制字符,例:get[4] = {0x61,0x61,0x62,0x62}; → put[4]={'a','a','b','b'};

typedef unsigned char uint8_t;
char data[64];
uint8_t *hex_to_char(char *str,uint32_t len)
{
    char *hex_buf = str;
    uint8_t *hex = (uint8_t *)data;
    for (int i = 0; i < len; i++)
    {
		if ((hex_buf[i] >= 0x30) && (hex_buf[i] <= 0x39))      //0--9
			hex_buf[i] -= 0x30;
		else if ((hex_buf[i] >= 0x41) && (hex_buf[i] <= 0x46)) //a--z
			hex_buf[i] -= 0x37;
		else if ((hex_buf[i] >= 0x61) && (hex_buf[i] <= 0x66)) //a--z
			hex_buf[i] -= 0x57;
		else
			hex_buf[i] = 0xff;
    }
    memcpy(hex, hex_buf, len);
 
    return hex;
}

到此这篇关于c语言16进制与ascii字符相互转换的文章就介绍到这了,更多相关c语言16进制与ascii字符转换内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!