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?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With