C ++位字符串到int的转换

Geo*_*rge 2 c++

我正在尝试将长度为'sLength'的位字符串(bitString)转换为int。以下代码对我的计算机工作正常。在任何情况下都可能不起作用?

int toInt(string bitString, int sLength){

    int tempInt;
    int num=0;
    for(int i=0; i<sLength; i++){
        tempInt=bitString[i]-'0';
        num=num+tempInt * pow(2,(sLength-1-i));
    }

    return num;
}
Run Code Online (Sandbox Code Playgroud)

提前致谢

Ria*_*iaD 5

pow与双打比赛。结果可能不正确。请改用位运算

num |= (1 << (sLength-1-i)) * tempInt;
Run Code Online (Sandbox Code Playgroud)

也不要忘记bitString包含“ 0”和“ 1”以外的符号或太长的情况