C++ most efficient way to convert string to int (faster than atoi)

后端 未结 10 957
遥遥无期
遥遥无期 2020-12-04 17:04

As mentioned in the title, I\'m looking for something that can give me more performance than atoi. Presently, the fastest way I know is

atoi(mystring.c_str(         


        
10条回答
  •  春和景丽
    2020-12-04 17:25

    A faster convert function only for positive integers without error checking.

    Multiplication is always slower that sum and shift, therefore change multiply with shift.

    int fast_atoi( const char * str )
    {
        int val = 0;
        while( *str ) {
            val = (val << 3) + (val << 1) + (*str++ - '0');
        }
        return val;
    }
    

提交回复
热议问题