From 7f54a348a5eb5087258e7457452eda32379daac3 Mon Sep 17 00:00:00 2001 From: lohhiiccc Date: Thu, 23 Apr 2026 15:54:46 +0200 Subject: [PATCH] fix: parse_hex.c --- src/parse_utils/parse_hex.c | 23 +++++++++++++++++++---- tests/parse_utils/test_parse_hex.c | 4 ++-- 2 files changed, 21 insertions(+), 6 deletions(-) diff --git a/src/parse_utils/parse_hex.c b/src/parse_utils/parse_hex.c index a94f8a2..0d31cd4 100644 --- a/src/parse_utils/parse_hex.c +++ b/src/parse_utils/parse_hex.c @@ -11,23 +11,38 @@ cli_parse_hex(const char *str, uint8_t *out, size_t max_len, size_t *out_len) { size_t str_len; size_t byte_count; + size_t pos = 0; + size_t i; if (NULL == str || '\0' == str[0]) return 1; str_len = strlen(str); + byte_count = (str_len + 1) / 2; if (byte_count > max_len) return 1; + *out_len = 0; - for (size_t i = 0; i < str_len; i += 2) + + for (i = 0; i + 1 < str_len; i += 2) { int hi = hex_nibble(str[i]); - int lo = (i + 1 < str_len) ? hex_nibble(str[i + 1]) : 0; - + int lo = hex_nibble(str[i + 1]); if (hi < 0 || lo < 0) return 1; - out[(*out_len)++] = (uint8_t)(hi << 4 | lo); + out[pos++] = (uint8_t)((hi << 4) | lo); + (*out_len)++; } + + if (i < str_len) + { + int lo = hex_nibble(str[i]); + if (lo < 0) + return 1; + out[pos++] = (uint8_t)lo; + ++*out_len; + } + return 0; } diff --git a/tests/parse_utils/test_parse_hex.c b/tests/parse_utils/test_parse_hex.c index a6c41c1..0e6eb1a 100644 --- a/tests/parse_utils/test_parse_hex.c +++ b/tests/parse_utils/test_parse_hex.c @@ -27,7 +27,7 @@ Test(parse_hex, odd_length) cr_assert_eq(ret, 0); cr_assert_eq(len, 2); cr_assert_eq(out[0], 0xab); - cr_assert_eq(out[1], 0xc0); + cr_assert_eq(out[1], 0x0c); } /* Test 3: Single char */ @@ -39,7 +39,7 @@ Test(parse_hex, single_char) cr_assert_eq(ret, 0); cr_assert_eq(len, 1); - cr_assert_eq(out[0], 0xf0); + cr_assert_eq(out[0], 0x0f); } /* Test 4: Single byte */