From bc5cca7a8b810f995cc835c8b262c112ba6b62ae Mon Sep 17 00:00:00 2001 From: dragonmux Date: Wed, 20 Jul 2022 02:12:07 +0100 Subject: [PATCH] hex_utils: Cleaned up and fixed the type confusion that was going on --- src/hex_utils.c | 28 +++++++++++++--------------- 1 file changed, 13 insertions(+), 15 deletions(-) diff --git a/src/hex_utils.c b/src/hex_utils.c index e18df58..b87b733 100644 --- a/src/hex_utils.c +++ b/src/hex_utils.c @@ -26,16 +26,16 @@ static const char hexdigits[] = "0123456789abcdef"; -char * hexify(char *hex, const void *buf, size_t size) +char *hexify(char *hex, const void *buf, const size_t size) { - char *tmp = hex; - const uint8_t *b = buf; + char *dst = hex; + const uint8_t *const src = buf; - while (size--) { - *tmp++ = hexdigits[*b >> 4]; - *tmp++ = hexdigits[*b++ & 0xF]; + for (size_t idx = 0; idx < size; ++idx) { + *dst++ = hexdigits[src[idx] >> 4]; + *dst++ = hexdigits[src[idx] & 0xF]; } - *tmp++ = 0; + *dst++ = 0; return hex; } @@ -43,20 +43,18 @@ char * hexify(char *hex, const void *buf, size_t size) static uint8_t unhex_digit(char hex) { uint8_t tmp = hex - '0'; - if(tmp > 9) + if (tmp > 9) tmp -= 'A' - '0' - 10; - if(tmp > 16) + if (tmp > 16) tmp -= 'a' - 'A'; return tmp; } -char * unhexify(void *buf, const char *hex, size_t size) +char *unhexify(void *buf, const char *hex, const size_t size) { - uint8_t *b = buf; - while (size--) { - *b = unhex_digit(*hex++) << 4; - *b++ |= unhex_digit(*hex++); + uint8_t *const dst = buf; + for (size_t idx = 0; idx < size; ++idx, hex += 2) { + dst[idx] = (unhex_digit(hex[0]) << 4) | unhex_digit(hex[1]); } return buf; } -