blob: 95819518fdfc3404b7a213b35a608b19b35c59e4 (
plain)
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
|
/* This software was written by Dirk Engling <erdgeist@erdgeist.org>
It is considered beerware. Prost. Skol. Cheers or whatever.
$id$ */
/* System */
#include <stdint.h>
#include <string.h>
/* Opentracker */
#include "ot_hex.h"
int hex_value(int c) {
unsigned char u = (unsigned char)c;
if (u >= '0' && u <= '9')
return u - '0';
u |= 0x20; /* fold upper case onto lower, digits are already handled */
if (u >= 'a' && u <= 'f')
return u - 'a' + 10;
return -1;
}
int hex_isdigit(int c) { return hex_value(c) >= 0; }
char *hex_fromhash(char *dest, const uint8_t *hash) {
static const char digits[] = "0123456789ABCDEF";
char *d = dest;
size_t i;
for (i = 0; i < sizeof(ot_hash); ++i) {
*d++ = digits[hash[i] >> 4];
*d++ = digits[hash[i] & 15];
}
*d = 0;
return dest;
}
int hex_tohash(ot_hash hash, const char *src) {
uint8_t decoded[sizeof(ot_hash)];
size_t i;
for (i = 0; i < sizeof(ot_hash); ++i) {
int high, low;
/* Tested one character at a time so that a string ending early stops us
at its terminator rather than one byte past it */
if ((high = hex_value((unsigned char)src[2 * i])) < 0)
return 0;
if ((low = hex_value((unsigned char)src[2 * i + 1])) < 0)
return 0;
decoded[i] = (uint8_t)((high << 4) | low);
}
memcpy(hash, decoded, sizeof(decoded));
return 1;
}
|