Line data Source code
1 : /* CC0 license (public domain) - see LICENSE file for details */ 2 : #include <config.h> 3 : #include <hex.h> 4 : #include <stdio.h> 5 : #include <stdlib.h> 6 : 7 160366 : static bool char_to_hex(unsigned char *val, char c) 8 : { 9 160366 : if (c >= '0' && c <= '9') { 10 97880 : *val = c - '0'; 11 97880 : return true; 12 : } 13 62486 : if (c >= 'a' && c <= 'f') { 14 60186 : *val = c - 'a' + 10; 15 60186 : return true; 16 : } 17 2300 : if (c >= 'A' && c <= 'F') { 18 2168 : *val = c - 'A' + 10; 19 2168 : return true; 20 : } 21 : return false; 22 : } 23 : 24 8094 : bool hex_decode(const char *str, size_t slen, void *buf, size_t bufsize) 25 : { 26 8094 : unsigned char v1, v2; 27 8094 : unsigned char *p = buf; 28 : 29 88211 : while (slen > 1) { 30 80249 : if (!char_to_hex(&v1, str[0]) || !char_to_hex(&v2, str[1])) 31 132 : return false; 32 80117 : if (!bufsize) 33 : return false; 34 80117 : *(p++) = (v1 << 4) | v2; 35 80117 : str += 2; 36 80117 : slen -= 2; 37 80117 : bufsize--; 38 : } 39 7962 : return slen == 0 && bufsize == 0; 40 : } 41 : 42 262408 : static char hexchar(unsigned int val) 43 : { 44 262408 : if (val < 10) 45 218156 : return '0' + val; 46 44252 : if (val < 16) 47 44252 : return 'a' + val - 10; 48 0 : abort(); 49 : } 50 : 51 5641 : bool hex_encode(const void *buf, size_t bufsize, char *dest, size_t destsize) 52 : { 53 5641 : size_t used = 0; 54 : 55 5641 : if (destsize < 1) 56 : return false; 57 : 58 136845 : while (used < bufsize) { 59 131204 : unsigned int c = ((const unsigned char *)buf)[used]; 60 131204 : if (destsize < 3) 61 : return false; 62 131204 : *(dest++) = hexchar(c >> 4); 63 131204 : *(dest++) = hexchar(c & 0xF); 64 131204 : used++; 65 131204 : destsize -= 2; 66 : } 67 5641 : *dest = '\0'; 68 : 69 5641 : return used + 1; 70 : }