Search code examples
c++stringbinarydecimalradix

How to convert a string containing only 0 or 1 into a binary variable?


How to convert a C++ string (containing only "0" or "1") to binary data directly according to its literal value?

For example, I have a string str, it's value is 0010010. Now I want to convert this string to a binary form variable, or a decimal variable equal to 0b0010010 (is 18).

int main() {
    string str_1 = "001";
    string str_2 = "0010";
    string str = str_1 + str_2;
    cout << str << endl;

    int i = stoi(str);
    double d = stod(str);
    cout << i << " and " << d << endl;
}

I tried stoi and stod, but they all can't work. They all treated binary 0b0010010 as decimal 10010. So how can I achieve this requirement? Thanks a lot!


Solution

  • std::stoi has an optional second argument to give you information about where the parsing stopped, and an optional third argument for passing the base of the conversion.

    int i = stoi(str, nullptr, 2);
    

    This should work.


    Corollary: If in doubt, check the documentation. ;-)