I am writing a string parser and the thought occurred to me that there might be some really interesting ways to convert an ASCII hexadecimal character [0-9A-Fa-f] to it’s numeric value.
What are the quickest, shortest, most elegant or most obscure ways to convert [0-9A-Fa-f] to it’s value between 0 and 15?
Assume, if you like, that the character is a valid hex character.
I have no chance so I’ll have a go at the most boring.
( c <= '9' ) ? ( c - '0' ) : ( (c | '\x60') - 'a' + 10 )
(c&15)+(c>>6)*9In response to “How does it work”, it throws away enough bits so that the numbers map to [0:9] and the letters map to [1:6], then adds 9 for the letters. The
c>>6is a stand-in forif (c >= 64) ....