2016-05-16 103 views
7

一些我需要解析的std::string包含二進制格式的數字,如:的std :: string流解析以二進制格式

0b01101101 

我知道,我可以使用std::hex格式說明解析數字以十六進制格式。

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

是否有相當於二進制格式的東西?

+0

你可以使用'std :: bitset'的字符串構造函數。 –

+0

二進制沒有等價的操作符。 – user2079303

回答

10

您可以使用std::bitset string constructor和轉換bistet至數:

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 
-1

你可以嘗試使用std::bitset

例如:

跳過兩個首字節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; 
+0

並從字符串解析? –

+0

這不是OP中所要求的。請再讀一遍。 –

+0

在刪除兩個「string」的第一個符號後,您可以將'string'解析爲'bitset'。 – proton