summaryrefslogtreecommitdiff
path: root/ot_hex.c
blob: 17dd1effcb769b5fb2a2c841f688eb233f3adca9 (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
/* 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"

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;
}