summaryrefslogtreecommitdiff
path: root/ot_hex.c
diff options
context:
space:
mode:
Diffstat (limited to 'ot_hex.c')
-rw-r--r--ot_hex.c56
1 files changed, 56 insertions, 0 deletions
diff --git a/ot_hex.c b/ot_hex.c
new file mode 100644
index 0000000..17dd1ef
--- /dev/null
+++ b/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 $id$ */
5
6/* System */
7#include <stdint.h>
8#include <string.h>
9
10/* Opentracker */
11#include "ot_hex.h"
12
13static int fromhex(unsigned char c) {
14 if (c >= '0' && c <= '9')
15 return c - '0';
16 c |= 0x20; /* fold upper case onto lower, digits are already handled */
17 if (c >= 'a' && c <= 'f')
18 return c - 'a' + 10;
19 return -1;
20}
21
22int hex_isdigit(int c) { return fromhex((unsigned char)c) >= 0; }
23
24char *hex_fromhash(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_tohash(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 = fromhex((unsigned char)src[2 * i])) < 0)
47 return 0;
48 if ((low = fromhex((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}