From c22fa15f5c44a43e291c15f737515e35fb9dc6ba Mon Sep 17 00:00:00 2001 From: Dirk Engling Date: Sat, 24 Oct 2026 02:00:42 +0200 Subject: Move all code converting between binary and hex representation to its own unit --- ot_hex.c | 56 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 ot_hex.c (limited to 'ot_hex.c') 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 @@ +/* This software was written by Dirk Engling + It is considered beerware. Prost. Skol. Cheers or whatever. + + $id$ */ + +/* System */ +#include +#include + +/* Opentracker */ +#include "ot_hex.h" + +static int fromhex(unsigned char c) { + if (c >= '0' && c <= '9') + return c - '0'; + c |= 0x20; /* fold upper case onto lower, digits are already handled */ + if (c >= 'a' && c <= 'f') + return c - 'a' + 10; + return -1; +} + +int hex_isdigit(int c) { return fromhex((unsigned char)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 = fromhex((unsigned char)src[2 * i])) < 0) + return 0; + if ((low = fromhex((unsigned char)src[2 * i + 1])) < 0) + return 0; + + decoded[i] = (uint8_t)((high << 4) | low); + } + + memcpy(hash, decoded, sizeof(decoded)); + return 1; +} -- cgit v1.3