fix: parse_hex.c
This commit is contained in:
parent
d39210fe74
commit
7f54a348a5
2 changed files with 21 additions and 6 deletions
|
|
@ -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;
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -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 */
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue