123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- #ifndef HEX_H
- #define HEX_H
- #include <api.h>
- #include <assert.h>
- #include <stddef.h>
- #include <stdint.h>
- static inline __attribute__((always_inline))
- char * __bytes2hexstr(void * hex, size_t size, char *str, size_t len)
- {
- static char * ch = "0123456789abcdef";
- __UNUSED(len);
- assert(len >= size * 2 + 1);
- for (size_t i = 0 ; i < size ; i++) {
- unsigned char h = ((unsigned char *) hex)[i];
- str[i * 2] = ch[h / 16];
- str[i * 2 + 1] = ch[h % 16];
- }
- str[size * 2] = 0;
- return str;
- }
- #define IS_INDEXABLE(arg) (sizeof((arg)[0]))
- #define IS_ARRAY(arg) (IS_INDEXABLE(arg) > 0 && (((void *) &(arg)) == ((void *) (arg))))
- static inline __attribute__((always_inline))
- int8_t hex2dec(char c) {
- if (c >= 'A' && c <= 'F')
- return c - 'A' + 10;
- else if (c >= 'a' && c <= 'f')
- return c - 'a' + 10;
- else if (c >= '0' && c <= '9')
- return c - '0';
- else
- return -1;
- }
- #define BYTES2HEXSTR(array, str, len) ({ \
- static_assert(IS_ARRAY(array), "`array` must be an array"); \
- __bytes2hexstr((array), sizeof(array), str, len);})
- #define ALLOCA_BYTES2HEXSTR(array) \
- (BYTES2HEXSTR(array, __alloca(sizeof(array) * 2 + 1), sizeof(array) * 2 + 1))
- #endif
|