Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
Download
58 views
1
#include "hex.h"
2
3
/*
4
All of this stuff is borrowed from here:
5
6
https://nachtimwald.com/2017/09/24/hex-encode-and-decode-in-c/
7
*/
8
9
int hexchr2bin(const char hex, char *out)
10
{
11
if (out == NULL)
12
return 0;
13
14
if (hex >= '0' && hex <= '9') {
15
*out = hex - '0';
16
} else if (hex >= 'A' && hex <= 'F') {
17
*out = hex - 'A' + 10;
18
} else if (hex >= 'a' && hex <= 'f') {
19
*out = hex - 'a' + 10;
20
} else {
21
return 0;
22
}
23
24
return 1;
25
}
26
27
28
char *bin2hex(const unsigned char *bin, size_t len)
29
{
30
char *out;
31
size_t i;
32
33
if (bin == NULL || len == 0)
34
return NULL;
35
36
out = malloc(len*2+1);
37
for (i=0; i<len; i++) {
38
out[i*2] = "0123456789ABCDEF"[bin[i] >> 4];
39
out[i*2+1] = "0123456789ABCDEF"[bin[i] & 0x0F];
40
}
41
out[len*2] = '\0';
42
43
return out;
44
}
45
46
size_t hexs2bin(const char *hex, unsigned char **out)
47
{
48
size_t len;
49
char b1;
50
char b2;
51
size_t i;
52
53
if (hex == NULL || *hex == '\0' || out == NULL)
54
return 0;
55
56
len = strlen(hex);
57
if (len % 2 != 0)
58
return 0;
59
len /= 2;
60
61
*out = malloc(len);
62
memset(*out, 'A', len);
63
for (i=0; i<len; i++) {
64
if (!hexchr2bin(hex[i*2], &b1) || !hexchr2bin(hex[i*2+1], &b2)) {
65
return 0;
66
}
67
(*out)[i] = (b1 << 4) | b2;
68
}
69
return len;
70
}
71
72
73
74