kit

kit
git clone https://git.ryansepassi.com/git/kit.git
Log | Files | Refs | README

dist.c (1032B)


      1 #include "dist.h"
      2 
      3 static char dist_hex_digit(unsigned v) {
      4   return (char)(v < 10u ? '0' + v : 'a' + (v - 10u));
      5 }
      6 
      7 void dist_hex_encode(char* out, const uint8_t* in, size_t n) {
      8   size_t i;
      9   for (i = 0; i < n; ++i) {
     10     out[2 * i] = dist_hex_digit((unsigned)(in[i] >> 4));
     11     out[2 * i + 1] = dist_hex_digit((unsigned)(in[i] & 0xfu));
     12   }
     13   out[2 * n] = '\0';
     14 }
     15 
     16 static int dist_hex_val(char c, unsigned* out) {
     17   if (c >= '0' && c <= '9') {
     18     *out = (unsigned)(c - '0');
     19     return DIST_OK;
     20   }
     21   if (c >= 'a' && c <= 'f') {
     22     *out = (unsigned)(c - 'a') + 10u;
     23     return DIST_OK;
     24   }
     25   if (c >= 'A' && c <= 'F') {
     26     *out = (unsigned)(c - 'A') + 10u;
     27     return DIST_OK;
     28   }
     29   return DIST_ERR;
     30 }
     31 
     32 int dist_hex_decode(uint8_t* out, const char* in, size_t n) {
     33   size_t i;
     34   for (i = 0; i < n; ++i) {
     35     unsigned hi, lo;
     36     if (dist_hex_val(in[2 * i], &hi) != DIST_OK) return DIST_ERR;
     37     if (dist_hex_val(in[2 * i + 1], &lo) != DIST_OK) return DIST_ERR;
     38     out[i] = (uint8_t)((hi << 4) | lo);
     39   }
     40   return DIST_OK;
     41 }