3

長さ '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;
}

前もって感謝します

4

6 に答える 6

3

または、標準ライブラリに面倒な作業を任せることもできます。

#include <bitset>
#include <string>
#include <sstream>
#include <climits>

// note the result is always unsigned
unsigned long toInt(std::string const &s) {
    static const std::size_t MaxSize = CHAR_BIT*sizeof(unsigned long);
    if (s.size() > MaxSize) return 0; // handle error or just truncate?

    std::bitset<MaxSize> bits;
    std::istringstream is(s);
    is >> bits;
    return bits.to_ulong();
}
于 2013-08-08T17:46:55.073 に答える
0
for (std::string::reverse_iterator it = bitString.rbegin();
    it != bitString.rend(); ++it) {
    num *= 2;
    num += *it == '1' ? 1 : 0;
}
于 2013-08-08T17:34:31.350 に答える