19#ifndef PROTOCORE_HEX_H
20#define PROTOCORE_HEX_H
25static const char *
const PC_HEX_LOWER =
"0123456789abcdef";
27static const char *
const PC_HEX_UPPER =
"0123456789ABCDEF";
32 return (upper ? PC_HEX_UPPER : PC_HEX_LOWER)[nibble & 0x0Fu];
38 if (c >=
'0' && c <=
'9')
40 return (int8_t)(c -
'0');
42 if (c >=
'a' && c <=
'f')
44 return (int8_t)(c -
'a' + 10);
46 if (c >=
'A' && c <=
'F')
48 return (int8_t)(c -
'A' + 10);
64 for (uint32_t probe = v; probe >= 16u; probe >>= 4)
68 for (uint8_t i = digits; i > 0; i--)
70 out[i - 1] = PC_HEX_LOWER[v & 0x0Fu];
83inline void pc_hex_encode(
const uint8_t *in, uint32_t n,
char *out,
bool upper =
false)
85 const char *digits = upper ? PC_HEX_UPPER : PC_HEX_LOWER;
86 for (uint32_t i = 0; i < n; i++)
88 out[2 * i] = digits[(in[i] >> 4) & 0x0Fu];
89 out[2 * i + 1] = digits[in[i] & 0x0Fu];
100inline int32_t
pc_hex_decode(
const char *in, uint32_t hexlen, uint8_t *out, uint32_t out_cap)
102 if ((hexlen % 2) != 0 || (hexlen / 2) > out_cap)
106 for (uint32_t i = 0; i < hexlen; i += 2)
110 if (hi < 0 || lo < 0)
114 out[i / 2] = (uint8_t)((hi << 4) | lo);
116 return (int32_t)(hexlen / 2);
char pc_hex_digit(uint8_t nibble, bool upper=false)
Low nibble of nibble as a hex character, uppercase when upper.
uint8_t pc_hex_u32(uint32_t v, char *out)
Write v into out as lowercase hex digits, most significant first, and return the digit count (1....
void pc_hex_encode(const uint8_t *in, uint32_t n, char *out, bool upper=false)
Write n bytes of in into out as 2 * n hex characters plus a NUL.
int32_t pc_hex_decode(const char *in, uint32_t hexlen, uint8_t *out, uint32_t out_cap)
Read exactly hexlen hex characters from in into out as hexlen / 2 bytes.
int8_t pc_hex_val(char c)
Hex character c as 0..15, or -1 when c is not a hex digit of either case.