summaryrefslogtreecommitdiff
path: root/src/ot_hex.c
diff options
context:
space:
mode:
Diffstat (limited to 'src/ot_hex.c')
-rw-r--r--src/ot_hex.c56
1 files changed, 56 insertions, 0 deletions
diff --git a/src/ot_hex.c b/src/ot_hex.c
new file mode 100644
index 0000000..b537094
--- /dev/null
+++ b/src/ot_hex.c
@@ -0,0 +1,56 @@
1/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
2 It is considered beerware. Prost. Skol. Cheers or whatever. */
3
4/* System */
5#include <stdint.h>
6#include <string.h>
7
8/* Opentracker */
9#include "ot_hex.h"
10
11int hex_value(int c) {
12 unsigned char u = (unsigned char)c;
13
14 if (u >= '0' && u <= '9')
15 return u - '0';
16 u |= 0x20; /* fold upper case onto lower, digits are already handled */
17 if (u >= 'a' && u <= 'f')
18 return u - 'a' + 10;
19 return -1;
20}
21
22int hex_isdigit(int c) { return hex_value(c) >= 0; }
23
24char *hex_from_hash(char *dest, const uint8_t *hash) {
25 static const char digits[] = "0123456789ABCDEF";
26 char *d = dest;
27 size_t i;
28
29 for (i = 0; i < sizeof(ot_hash); ++i) {
30 *d++ = digits[hash[i] >> 4];
31 *d++ = digits[hash[i] & 15];
32 }
33 *d = 0;
34 return dest;
35}
36
37int hex_to_hash(ot_hash hash, const char *src) {
38 uint8_t decoded[sizeof(ot_hash)];
39 size_t i;
40
41 for (i = 0; i < sizeof(ot_hash); ++i) {
42 int high, low;
43
44 /* Tested one character at a time so that a string ending early stops us
45 at its terminator rather than one byte past it */
46 if ((high = hex_value((unsigned char)src[2 * i])) < 0)
47 return 0;
48 if ((low = hex_value((unsigned char)src[2 * i + 1])) < 0)
49 return 0;
50
51 decoded[i] = (uint8_t)((high << 4) | low);
52 }
53
54 memcpy(hash, decoded, sizeof(decoded));
55 return 1;
56}