Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ bit string to int conversion

Tags:

c++

I am trying to convert a bit string (bitString) of length 'sLength' to an int. The following code works fine for me in my computer. Is there any case where it may not work?

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;
}

Thanks in advance

like image 930
George Avatar asked Aug 16 '26 06:08

George


2 Answers

pow works with doubles. Result may be inaccurate. Use bit arithmetic instead

num |= (1 << (sLength-1-i)) * tempInt;

Don't also forget about cases when bitString contains symbols other than '0' and '1' or too long

like image 121
RiaD Avatar answered Aug 17 '26 19:08

RiaD


Or, you can let the standard library do the heavy lifting:

#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();
}
like image 24
Useless Avatar answered Aug 17 '26 20:08

Useless