
From: Lukas Funke lukas.funke@weidmueller.com
Add a 'hextobarray()' function which converts a hex string to it's memory representation. This can be used to represent large integer numbers or bitmasks which do not fit in a regular unsigned long value.
Signed-off-by: Lukas Funke lukas.funke@weidmueller.com ---
(no changes since v1)
include/vsprintf.h | 7 +++++++ lib/strto.c | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 42 insertions(+)
diff --git a/include/vsprintf.h b/include/vsprintf.h index ed8a060ee1..82c8bf029e 100644 --- a/include/vsprintf.h +++ b/include/vsprintf.h @@ -368,4 +368,11 @@ int vsscanf(const char *inp, char const *fmt0, va_list ap); */ int sscanf(const char *buf, const char *fmt, ...);
+/** + * hextobarray - Convert a hex-string to a byte array + * @cp: hex string to convert + * Return: a pointer to a byte array, -ENOMEM on error + */ +uchar *hextobarray(const char *cp); + #endif diff --git a/lib/strto.c b/lib/strto.c index 5157332d6c..eb507e4ab8 100644 --- a/lib/strto.c +++ b/lib/strto.c @@ -13,6 +13,7 @@ #include <malloc.h> #include <vsprintf.h> #include <linux/ctype.h> +#include <linux/err.h>
/* from lib/kstrtox.c */ static const char *_parse_integer_fixup_radix(const char *s, uint *basep) @@ -73,6 +74,40 @@ ulong simple_strtoul(const char *cp, char **endp, uint base) return result; }
+uchar *hextobarray(const char *cp) +{ + int i, len; + __maybe_unused unsigned int base; + __maybe_unused const char *endptr; + unsigned char *array; + + len = strlen(cp); + array = (unsigned char *)malloc(len); + if (!array) + return ERR_PTR(-ENOMEM); + + memset(array, 0, len); + +#if __BYTE_ORDER == __LITTLE_ENDIAN + endptr = (cp + len - 1); + for (i = 0; i < len && endptr > cp; i++) { + array[i] |= decode_digit(*(endptr)); + endptr--; + array[i] |= decode_digit(*endptr) << 4; + endptr--; + } +#else + cp = _parse_integer_fixup_radix(cp, &base); + for (i = 0; i < len && *cp; i++) { + array[i] |= decode_digit(*cp) << 4; + cp++; + array[i] |= decode_digit(*cp); + cp++; + } +#endif + return array; +} + ulong hextoul(const char *cp, char **endp) { return simple_strtoul(cp, endp, 16);