algorithmhex

Fastest way to decode a hexadecimal digit


I am looking for the fastest way to get the decimal value of a hexadecimal ASCII character, i.e. one that is guaranteed to appear in the following string (it can be lower or upper case, but no white space):

0123456789ABCDEFabcdef

So far, the best formula I've come up with is:

char c = 'd';  // or any other hex character
int value = (((c & 0x1F) + 9) % 25;

Note that it is branch-free, but it does contain an expensive modulo operation.

Can I do better?


Solution

  • (d & 0xf) + ((d & 0x40) >> 3) + ((d & 0x40) >> 6)
    

    Very straightforward bit fiddling.

    Demo

    A slightly different variant

    (d & 0xf) + (d >> 6) + ((d >> 6) << 3)
    

    saves another bitwise and operation.

    Both variants basically multiply the 6th bit by 9 (same as in the Mark Ransom's answer but without hardware multiplication).