C语⾔16进制与ASCII字符相互转换
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;
}
c语言中的sprintf用法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字符转换内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论