hex.h (1296B)
1 2 static inline int char_to_hex(unsigned char *val, char c) 3 { 4 if (c >= '0' && c <= '9') { 5 *val = c - '0'; 6 return 1; 7 } 8 if (c >= 'a' && c <= 'f') { 9 *val = c - 'a' + 10; 10 return 1; 11 } 12 if (c >= 'A' && c <= 'F') { 13 *val = c - 'A' + 10; 14 return 1; 15 } 16 return 0; 17 } 18 19 static inline int hex_decode(const char *str, size_t slen, void *buf, size_t bufsize) 20 { 21 unsigned char v1, v2; 22 unsigned char *p = buf; 23 24 while (slen > 1) { 25 if (!char_to_hex(&v1, str[0]) || !char_to_hex(&v2, str[1])) 26 return 0; 27 if (!bufsize) 28 return 0; 29 *(p++) = (v1 << 4) | v2; 30 str += 2; 31 slen -= 2; 32 bufsize--; 33 } 34 return slen == 0 && bufsize == 0; 35 } 36 37 static inline size_t hex_str_size(size_t bytes) 38 { 39 return 2 * bytes + 1; 40 } 41 42 static inline char hexchar(unsigned int val) 43 { 44 if (val < 10) 45 return '0' + val; 46 if (val < 16) 47 return 'a' + val - 10; 48 abort(); 49 } 50 51 static inline int hex_encode(const void *buf, size_t bufsize, char *dest, size_t destsize) 52 { 53 size_t i; 54 55 if (destsize < hex_str_size(bufsize)) { 56 fprintf(stderr, "hexencode: destsize(%zu) < hex_str_size(%zu)\n", destsize, hex_str_size(bufsize)); 57 return 0; 58 } 59 60 for (i = 0; i < bufsize; i++) { 61 unsigned int c = ((const unsigned char *)buf)[i]; 62 *(dest++) = hexchar(c >> 4); 63 *(dest++) = hexchar(c & 0xF); 64 } 65 *dest = '\0'; 66 67 return 1; 68 } 69