Std :: string stream parses a number in binary format

I need to parse std::string containing a binary number, like this:

 0b01101101 

I know that I can use the std :: hex format specifier to parse numbers in hexadecimal format.

 std::string number = "0xff"; number.erase(0, 2); std::stringstream sstream(number); sstream << std::hex; int n; sstream >> n; 

Is there something equivalent for binary format?

+7
c ++ format binary c ++ 11 stringstream
source share
2 answers

You can use the std::bitset string constructor and convert the bistet to a number:

 std::string number = "0b101"; //We need to start reading from index 2 to skip 0b //Or we can erase that substring beforehand int n = std::bitset<32>(number, 2).to_ulong(); //Be careful with potential overflow 
+10
source share

You can try using std::bitset

eg:

skip the first two bytes of 0b

 #include <bitset> ... std::string s = "0b0111"; std::bitset<4>x(s,2); //pass string s to parsing, skip first two signs std::cout << x; char a = -20; std::bitset<8> x(a); std::cout << x; short b = -427; std::bitset<16> y(c); std::cout << y; 
-one
source share

All Articles