I\'m trying to convert a hex char
to integer as fast as possible.
This is only one line:
int x = atoi(hex.c_str);
Is there a faster way
Assuming that your function is called for a valid hex digit, it will cost in average at least 8 comparison operations (and perhap's 7 jumps). Pretty expensive.
An alternative would be the more compact:
if (number >= '0' && number<='9')
return number-'0';
else if (number >= 'a' && number <='f')
return number-'a'+0x0a;
else return -1;
Yet another alternative would be to use a lookup table (trade space against speed), that you would initialise only once, and then access directly:
if (number>=0)
return mytable[number];
else return -1;
If you want to convert more than one digit at a time, you could have a look at this question)
Edit: benchmark
Following Ike's observations, Ive written a small informal benchmark (available online here), that you can run on your favourite compiler.
Conclusions: