What's the fastest way to convert hex to integer in C++?

后端 未结 6 654
甜味超标
甜味超标 2021-02-01 08:52

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

6条回答
  •  不要未来只要你来
    2021-02-01 09:32

    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:

    • The lookup table is always the winner
    • The switch better than the if-chain.
    • With msvc2015 (release), the second best is my compact version, surprisingly followed closely by the map version of 101010.
    • With gcc on ideone, the second is the switch version followed by the compact version.

提交回复
热议问题