Reputation: 10499
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?
Upvotes: 8
Views: 1643
Reputation: 341
You can try to use std::bitset
for example:
skip two first bytes 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;
Upvotes: 0
Reputation: 8783
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
Upvotes: 11