-
Notifications
You must be signed in to change notification settings - Fork 0
/
hex.c
108 lines (96 loc) · 2.73 KB
/
hex.c
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
/************************************************************************
* 二进制字节数组转换十六进制字符串函数
* 输入:
* data 二进制字节数组
* size 二进制字节数组长度
* 输出:
* 十六进制字符串,需要free函数释放空间,失败返回NULL
*
* author: tonglulin@gmail.com by www.qmailer.net
************************************************************************/
char *bin2hex(unsigned char *data, int size)
{
int i = 0;
int v = 0;
char *p = NULL;
char *buf = NULL;
char base_char = 'A';
buf = p = (char *)malloc(size * 2 + 1);
for (i = 0; i < size; i++) {
v = data[i] >> 4;
*p++ = v < 10 ? v + '0' : v - 10 + base_char;
v = data[i] & 0x0f;
*p++ = v < 10 ? v + '0' : v - 10 + base_char;
}
*p = '\0';
return buf;
}
/************************************************************************
* 十六进制字符串转换二进制字节数组
* 输入:
* data 十六进制字符串
* size 十六进制字符串长度,2的倍数
* outlen 转换后的二进制字符数组长度
* 输出:
* 二进制字符数组,需要free函数释放空间,失败返回NULL
*
* author: tonglulin@gmail.com by www.qmailer.net
************************************************************************/
unsigned char *hex2bin(const char *data, int size, int *outlen)
{
int i = 0;
int len = 0;
char char1 = '\0';
char char2 = '\0';
unsigned char value = 0;
unsigned char *out = NULL;
if (size % 2 != 0) {
return NULL;
}
len = size / 2;
out = (unsigned char *)malloc(len * sizeof(char) + 1);
if (out == NULL) {
return NULL;
}
while (i < len) {
char1 = *data;
if (char1 >= '0' && char1 <= '9') {
value = (char1 - '0') << 4;
}
else if (char1 >= 'a' && char1 <= 'f') {
value = (char1 - 'a' + 10) << 4;
}
else if (char1 >= 'A' && char1 <= 'F') {
value = (char1 - 'A' + 10) << 4;
}
else {
free(out);
return NULL;
}
data++;
char2 = *data;
if (char2 >= '0' && char2 <= '9') {
value |= char2 - '0';
}
else if (char2 >= 'a' && char2 <= 'f') {
value |= char2 - 'a' + 10;
}
else if (char2 >= 'A' && char2 <= 'F') {
value |= char2 - 'A' + 10;
}
else {
free(out);
return NULL;
}
data++;
*(out + i++) = value;
}
*(out + i) = '\0';
if (outlen != NULL) {
*outlen = i;
}
return out;
}