diff options
| author | Dirk Engling <erdgeist@erdgeist.org> | 2026-11-02 20:50:24 +0100 |
|---|---|---|
| committer | Dirk Engling <erdgeist@erdgeist.org> | 2026-11-02 21:14:02 +0100 |
| commit | ad541c67761b8aa6da1566802c347cac4018d0c2 (patch) | |
| tree | a9166fa9d349911d69a6948e53b05344dcc348a0 /src/ot_hex.c | |
| parent | c679ff8a3b1418a5960cc49ba6458a0007df54fa (diff) | |
Move the build sources into src/
Diffstat (limited to 'src/ot_hex.c')
| -rw-r--r-- | src/ot_hex.c | 56 |
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 | |||
| 11 | int 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 | |||
| 22 | int hex_isdigit(int c) { return hex_value(c) >= 0; } | ||
| 23 | |||
| 24 | char *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 | |||
| 37 | int 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 | } | ||
