Re: [PATCH 01/10] lib: introduce common method to convert hexdigits

From: Andrew Morton
Date: Fri Apr 30 2010 - 15:08:26 EST


On Fri, 30 Apr 2010 12:34:00 +0300
Andy Shevchenko <ext-andriy.shevchenko@xxxxxxxxx> wrote:

> /**
> + * hex_to_bin - convert a hex digit to its real value
> + * @ch: ascii character represents hex digit
> + *
> + * hex_to_bin() converts one hex digit to its actual value or -1 in case of bad
> + * input.
> + */
> +int hex_to_bin(char ch)
> +{
> + if ((ch >= 'a') && (ch <= 'f'))
> + return ch - 'a' + 10;
> + if ((ch >= '0') && (ch <= '9'))
> + return ch - '0';
> + if ((ch >= 'A') && (ch <= 'F'))
> + return ch - 'A' + 10;
> + return -1;
> +}
> +EXPORT_SYMBOL(hex_to_bin);

I had to fiddle with it:

- use tolower(), saving 3 bytes!

- test the more common case first - it's quicker.

diff -puN lib/hexdump.c~lib-introduce-common-method-to-convert-hex-digits-fix lib/hexdump.c
--- a/lib/hexdump.c~lib-introduce-common-method-to-convert-hex-digits-fix
+++ a/lib/hexdump.c
@@ -24,12 +24,11 @@ EXPORT_SYMBOL(hex_asc);
*/
int hex_to_bin(char ch)
{
- if ((ch >= 'a') && (ch <= 'f'))
- return ch - 'a' + 10;
+ ch = tolower(ch);
if ((ch >= '0') && (ch <= '9'))
return ch - '0';
- if ((ch >= 'A') && (ch <= 'F'))
- return ch - 'A' + 10;
+ if ((ch >= 'a') && (ch <= 'f'))
+ return ch - 'a' + 10;
return -1;
}
EXPORT_SYMBOL(hex_to_bin);
_


Yielding

int hex_to_bin(char ch)
{
ch = tolower(ch);
if ((ch >= '0') && (ch <= '9'))
return ch - '0';
if ((ch >= 'a') && (ch <= 'f'))
return ch - 'a' + 10;
return -1;
}

--
To unsubscribe from this list: send the line "unsubscribe linux-kernel" in
the body of a message to majordomo@xxxxxxxxxxxxxxx
More majordomo info at http://vger.kernel.org/majordomo-info.html
Please read the FAQ at http://www.tux.org/lkml/