diff options
author | Simon Glass | 2021-07-24 09:03:35 -0600 |
---|---|---|
committer | Tom Rini | 2021-08-02 13:32:14 -0400 |
commit | 5a94546e1cb302842aa0f65be0bb3585fd010ccd (patch) | |
tree | 4cb611c1f330fd6d38be15e6cd13051540a2c03d /lib/strto.c | |
parent | ab833ef60a13b60bfa8e236ca774e91b22255a5a (diff) |
lib: Move common digit-parsing code into a function
The code to convert a character into a digit is repeated twice in this
file. Factor it out into a separate function. This also makes the code a
little easier to read.
Signed-off-by: Simon Glass <sjg@chromium.org>
Diffstat (limited to 'lib/strto.c')
-rw-r--r-- | lib/strto.c | 31 |
1 files changed, 24 insertions, 7 deletions
diff --git a/lib/strto.c b/lib/strto.c index 53886722138..b056b205c85 100644 --- a/lib/strto.c +++ b/lib/strto.c @@ -30,16 +30,33 @@ static const char *_parse_integer_fixup_radix(const char *s, unsigned int *base) return s; } +/** + * decode_digit() - Decode a single character into its numeric digit value + * + * This ignore case + * + * @ch: Character to convert (expects '0'..'9', 'a'..'f' or 'A'..'F') + * @return value of digit (0..0xf) or 255 if the character is invalid + */ +static uint decode_digit(int ch) +{ + if (!isxdigit(ch)) + return 256; + + ch = tolower(ch); + + return ch <= '9' ? ch - '0' : ch - 'a' + 0xa; +} + ulong simple_strtoul(const char *cp, char **endp, uint base) { ulong result = 0; - ulong value; + uint value; cp = _parse_integer_fixup_radix(cp, &base); - while (isxdigit(*cp) && (value = isdigit(*cp) ? *cp-'0' : (islower(*cp) - ? toupper(*cp) : *cp)-'A'+10) < base) { - result = result*base + value; + while (value = decode_digit(*cp), value < base) { + result = result * base + value; cp++; } @@ -136,12 +153,12 @@ unsigned long long ustrtoull(const char *cp, char **endp, unsigned int base) unsigned long long simple_strtoull(const char *cp, char **endp, unsigned int base) { - unsigned long long result = 0, value; + unsigned long long result = 0; + uint value; cp = _parse_integer_fixup_radix(cp, &base); - while (isxdigit(*cp) && (value = isdigit(*cp) ? *cp - '0' - : (islower(*cp) ? toupper(*cp) : *cp) - 'A' + 10) < base) { + while (value = decode_digit(*cp), value < base) { result = result * base + value; cp++; } |