forked from jonas/tig
-
Notifications
You must be signed in to change notification settings - Fork 0
/
hex.h
69 lines (59 loc) · 1.27 KB
/
hex.h
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
static inline int char_to_hex(unsigned char *val, char c)
{
if (c >= '0' && c <= '9') {
*val = c - '0';
return 1;
}
if (c >= 'a' && c <= 'f') {
*val = c - 'a' + 10;
return 1;
}
if (c >= 'A' && c <= 'F') {
*val = c - 'A' + 10;
return 1;
}
return 0;
}
static inline int hex_decode(const char *str, size_t slen, void *buf, size_t bufsize)
{
unsigned char v1, v2;
unsigned char *p = buf;
while (slen > 1) {
if (!char_to_hex(&v1, str[0]) || !char_to_hex(&v2, str[1]))
return 0;
if (!bufsize)
return 0;
*(p++) = (v1 << 4) | v2;
str += 2;
slen -= 2;
bufsize--;
}
return slen == 0 && bufsize == 0;
}
static inline size_t hex_str_size(size_t bytes)
{
return 2 * bytes + 1;
}
static inline char hexchar(unsigned int val)
{
if (val < 10)
return '0' + val;
if (val < 16)
return 'a' + val - 10;
abort();
}
static inline int hex_encode(const void *buf, size_t bufsize, char *dest, size_t destsize)
{
size_t i;
if (destsize < hex_str_size(bufsize)) {
fprintf(stderr, "hexencode: destsize(%zu) < hex_str_size(%zu)\n", destsize, hex_str_size(bufsize));
return 0;
}
for (i = 0; i < bufsize; i++) {
unsigned int c = ((const unsigned char *)buf)[i];
*(dest++) = hexchar(c >> 4);
*(dest++) = hexchar(c & 0xF);
}
*dest = '\0';
return 1;
}