今天看代码看到两种16进制字符串转字节数组的方法,现贴出来相当于做个笔记了。
第一种:
1 #include<string.h>
2 #include<stdio.h>
3
4 void hex_str_to_byte(char *hex_str, int length, unsigned char *result)
5 {
6 char h, l;
7 for(int i = 0; i < length/2; i++)
8 {
9 if(*hex_str < 58)
10 {
11 h = *hex_str - 48;
12 }
13 else if(*hex_str < 71)
14 {
15 h = *hex_str - 55;
16 }
17 else
18 {
19 h = *hex_str - 87;
20 }
21 hex_str++;
22 if(*hex_str < 58)
23 {
24 l = *hex_str - 48;
25 }
26 else if(*hex_str < 71)
27 {
28 l = *hex_str - 55;
29 }
30 else
31 {
32 l = *hex_str - 87;
33 }
34 hex_str++;
35 *result++ = h<<4|l;
36 }
37 }
38
39 int main()
40 {
41 char *str = "AB32333435363738393a3b3c3d3e3f40";
42 unsigned char temp[16] = {0};
43 hex_str_to_byte(str, strlen("AB32333435363738393a3b3c3d3e3f40"), temp);
44 for (int i = 0; i < 16; i++)
45 {
46 printf("%x ", temp[i]);
47 }
48 printf("\n");
49 return 0;
50 }
第二种:
36 #include<stdlib.h>
37 #include<string.h>
38 #include<stdio.h>
39 void hex_str_to_byte(char *in, int len, unsigned char *out)
40 {
41 char *str = (char *)malloc(len);
42 memset(str, 0, len);
43 memcpy(str, in, len);
44 for (int i = 0; i < len; i+=2)
45 {
46 //小写转大写
47 if(str[i] >= 'a' && str[i] <= 'f') str[i] = str[i] - 0x20;
48 if(str[i+1] >= 'a' && str[i] <= 'f') str[i+1] = str[i+1] - 0x20;
49 //处理第前4位
50 if(str[i] >= 'A' && str[i] <= 'F')
51 out[i/2] = (str[i]-'A'+10)<<4;
52 else
53 out[i/2] = (str[i] & ~0x30)<<4;
54 //处理后4位, 并组合起来
55 if(str[i+1] >= 'A' && str[i+1] <= 'F')
56 out[i/2] |= (str[i+1]-'A'+10);
57 else
58 out[i/2] |= (str[i+1] & ~0x30);
59 }
60 free(str);
61 }
62
63 int main()
64 {
65 char *str = "AB32333435363738393a3b3c3d3e3f40";
66 unsigned char temp[16] = {0};
67 hex_str_to_byte(str, strlen("AB32333435363738393a3b3c3d3e3f40"), temp);
68 for (int i = 0; i < 16; i++)
69 {
70 printf("%x ", temp[i]);
71 }
72 printf("\n");
73 return 0;
74 }