Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::string stream parse a number in binary format

I need to parse an std::string containing a number in binary format, such as:

0b01101101

I know that I can use the std::hex format specifier to parse numbers in the 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 the binary format?

like image 427
Nick Avatar asked May 16 '16 09:05

Nick


1 Answers

You can use std::bitset string constructor and convert bistet to 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
like image 193
Revolver_Ocelot Avatar answered Oct 23 '22 04:10

Revolver_Ocelot