概述:本文主要记录实现 16进制与字符串互相转换的逻辑与实现
参考博客:C语言快速互转HEX(16进制)和原始字符串/数组 – 晨旭的博客~
说明
16进制格式为 0x00、0x01……这样的形式
十进制格式为 0、1、2…… 这样的形式
主要参考 ASCII码一览表,ASCII码对照表,实现的内容就是 十进制到十六进制
的互相转换
实现
HexToByte
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include <stdio.h>
void from_hex(char *s, int l, char *d) { while(l--) { char* p = s+l; char* p2 = p-1; *(d+l/2) = ( (*p>'9'? *p+9 : *p) & 0x0f ) | ( (*p2>'9'? *p2+9 : *p2) << 4 ); l--; } }
int main () { char s[]= "6F6B6f6b"; char d[5]; d[4] = '\0'; from_hex(s,8,d); printf("%s",d); return 0; }
|
ByteToHex
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| #include <stdio.h> const char hex_table[] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' }; void to_hex(char *s, int l, char *d) { while(l--) { *(d+2*l+1) = hex_table[(*(s+l))&0x0f]; *(d+2*l) = hex_table[(*(s+l))>>4]; } }
static void bytesToHex(uint8 b[16], char *s) { static const char *hex = "0123456789abcdef"; int q, w;
for (q = 0, w = 0; q < 16; q++) { s[w++] = hex[(b[q] >> 4) & 0x0F]; s[w++] = hex[b[q] & 0x0F]; } s[w] = '\0'; }
int main () { char s[]= "1234abcd"; char d[1024]; d[8] = '\0'; to_hex(s,sizeof(s)/sizeof(char) - 1,d); printf("%s",d); return 0; }
|
关于 ASCII 转 HEX 我提出一点问题,在 https://www.onlinegdb.com/ 在线编译,运行上述代码,编译得到的结果略微有点问题:
可以看到小于 10 的数字的第一位都被3填充了。可能是因为栈空间默认初始化的时候都是被 0x00000011 这样的数据填充的。稍微修改了下,加了个判断如下所示:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| void to_hex(char *s, int l, char *d) { while(l--) { if(*s > '9') *d = hex_table[(*s >> 4) & 0x0f]; else *d = hex_table[(*s >> 4) & 0x00]; d++; *d = hex_table[*s & 0x0f]; s++; d++; } }
|
一种更高效的实现:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| #include <stdio.h>
void from_hex(char *s, int l, char *d) { while(l--) { *d = (*s>'9' ? *s+9 : *s) << 4; ++s; *d |= (*s>'9' ? *s+9 : *s) & 0x0F; ++s; ++d; } }
int main () { char s[]= "6F6B6f6b"; char d[5]; d[4] = '\0'; from_hex(s,4,d); printf("%s",d); return 0; }
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| #include <stdio.h> const char hex_table[] = { '0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F' }; void to_hex(char *s, int l, char *d) { while(l--) { *d = hex_table[*s >> 4 & 0]; d++; *d = hex_table[*s & 0x0f]; s++; d++; } } int main () { char s[]= "1234"; char d[9]; d[8] = '\0'; to_hex(s,4,d); printf("%s",d); return 0; }
|