C hex2bin bin2hex 常用转换

C 语言版本的 十六进制 与二进制 转换 函数
各个仓库中都要使用这个函数.

bin2hex

1
2
3
4
5
6
7
8
9
10
11
12
13
14
int bin2hex(const unsigned char *i, size_t l, unsigned char *o, size_t s)
{
static char hex2char[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
size_t pos = 0;
size_t walk = 0;
for(pos = 0; pos < l && walk < s-1; pos++)
{
unsigned char H = i[pos] >> 4;
unsigned char L = i[pos] & 0x0F;
o[walk++] = hex2char[H];
o[walk++] = hex2char[L];
}
return walk;
}

hex2bin

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
int hex2bin(const unsigned char *i, size_t l, unsigned char *o, size_t s)
{
size_t pos = 0;
size_t walk = 0;
unsigned char v = 0;
for(pos = 0; pos < l && walk/2 < s; pos++)
{
switch(i[pos])
{
case '-':
case ':':
continue;

case 'A' ... 'Z':
v |= i[pos] - 'A' +10;
break;

case 'a' ... 'z':
v |= i[pos] - 'a' +10;
break;

case '0' ... '9':
v |= i[pos] - '0';
break;

default:
continue;
}
o[walk/2] = v;
walk++;
v <<= 4;
}
return walk/2;
}