From 4836331924b5eb7f74e000d50c99bc12d513f8c7 Mon Sep 17 00:00:00 2001 From: Denys Vlasenko Date: Sun, 4 Apr 2010 15:29:32 +0200 Subject: libbb: factor out hex2bin() for infiniband address parser function old new delta hex2bin - 149 +149 in_ib 172 27 -145 Signed-off-by: Denys Vlasenko --- libbb/xfuncs.c | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) (limited to 'libbb/xfuncs.c') diff --git a/libbb/xfuncs.c b/libbb/xfuncs.c index aac46f414..aec165f06 100644 --- a/libbb/xfuncs.c +++ b/libbb/xfuncs.c @@ -122,6 +122,41 @@ char* FAST_FUNC bin2hex(char *p, const char *cp, int count) return p; } +/* Convert "[x]x[:][x]x[:][x]x[:][x]x" hex string to binary, no more than COUNT bytes */ +char* FAST_FUNC hex2bin(char *dst, const char *str, int count) +{ + errno = EINVAL; + while (*str && count) { + uint8_t val; + uint8_t c = *str++; + if (isdigit(c)) + val = c - '0'; + else if ((c|0x20) >= 'a' && (c|0x20) <= 'f') + val = (c|0x20) - ('a' - 10); + else + return NULL; + val <<= 4; + c = *str; + if (isdigit(c)) + val |= c - '0'; + else if ((c|0x20) >= 'a' && (c|0x20) <= 'f') + val |= (c|0x20) - ('a' - 10); + else if (c == ':' || c == '\0') + val >>= 4; + else + return NULL; + + *dst++ = val; + if (c != '\0') + str++; + if (*str == ':') + str++; + count--; + } + errno = (*str ? ERANGE : 0); + return dst; +} + /* Return how long the file at fd is, if there's any way to determine it. */ #ifdef UNUSED off_t FAST_FUNC fdlength(int fd) -- cgit v1.2.3