C语言16进制与ASCII字符转换
冷冰难暖 人气:61、把获取到的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; }
加载全部内容