From d7b5545748fde88ad6b67732308722a2565f5dcf Mon Sep 17 00:00:00 2001 From: Max Bruckner Date: Mon, 6 Feb 2017 23:01:18 +0100 Subject: [PATCH] parse_hex4: deduplicate into a for loop --- cJSON.c | 100 ++++++++++++++------------------------------------------ 1 file changed, 25 insertions(+), 75 deletions(-) diff --git a/cJSON.c b/cJSON.c index e2efd31..e0c1b57 100644 --- a/cJSON.c +++ b/cJSON.c @@ -362,84 +362,34 @@ static unsigned char *print_number(const cJSON *item, printbuffer *p) static unsigned parse_hex4(const unsigned char *str) { unsigned int h = 0; + size_t i = 0; - /* first digit */ - if ((*str >= '0') && (*str <= '9')) + for (i = 0; i < 4; i++) { - h += (unsigned int) (*str) - '0'; - } - else if ((*str >= 'A') && (*str <= 'F')) - { - h += (unsigned int) 10 + (*str) - 'A'; - } - else if ((*str >= 'a') && (*str <= 'f')) - { - h += (unsigned int) 10 + (*str) - 'a'; - } - else /* invalid */ - { - return 0; - } + /* parse digit */ + if ((*str >= '0') && (*str <= '9')) + { + h += (unsigned int) (*str) - '0'; + } + else if ((*str >= 'A') && (*str <= 'F')) + { + h += (unsigned int) 10 + (*str) - 'A'; + } + else if ((*str >= 'a') && (*str <= 'f')) + { + h += (unsigned int) 10 + (*str) - 'a'; + } + else /* invalid */ + { + return 0; + } - - /* second digit */ - h = h << 4; - str++; - if ((*str >= '0') && (*str <= '9')) - { - h += (unsigned int) (*str) - '0'; - } - else if ((*str >= 'A') && (*str <= 'F')) - { - h += (unsigned int) 10 + (*str) - 'A'; - } - else if ((*str >= 'a') && (*str <= 'f')) - { - h += (unsigned int) 10 + (*str) - 'a'; - } - else /* invalid */ - { - return 0; - } - - /* third digit */ - h = h << 4; - str++; - if ((*str >= '0') && (*str <= '9')) - { - h += (unsigned int) (*str) - '0'; - } - else if ((*str >= 'A') && (*str <= 'F')) - { - h += (unsigned int) 10 + (*str) - 'A'; - } - else if ((*str >= 'a') && (*str <= 'f')) - { - h += (unsigned int) 10 + (*str) - 'a'; - } - else /* invalid */ - { - return 0; - } - - /* fourth digit */ - h = h << 4; - str++; - if ((*str >= '0') && (*str <= '9')) - { - h += (unsigned int) (*str) - '0'; - } - else if ((*str >= 'A') && (*str <= 'F')) - { - h += (unsigned int) 10 + (*str) - 'A'; - } - else if ((*str >= 'a') && (*str <= 'f')) - { - h += (unsigned int) 10 + (*str) - 'a'; - } - else /* invalid */ - { - return 0; + if (i < 3) + { + /* shift left to make place for the next nibble */ + h = h << 4; + str++; + } } return h;