2016-05-16 20 views
7

ho bisogno di analizzare un std::string contenente un numero in formato binario, come ad esempio:flusso std :: string analizzare un numero in formato binario

0b01101101 

So che posso usare l'identificatore di formato std::hex per analizzare i numeri nel formato esadecimale.

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

Esiste qualcosa di equivalente per il formato binario?

+0

È può usare il costruttore di stringhe 'std :: bitset'. –

+0

Non esiste un manipolatore equivalente per binario. – user2079303

risposta

10

È possibile utilizzare std::bitset string constructor e convertire bistet al numero:

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

Si può cercare di utilizzare std::bitset

ad esempio:

saltare due primi byte 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

E analizzando da stringa? –

+0

Questo non è ciò che è stato richiesto nell'OP. Leggi di nuovo per favore. –

+0

è possibile analizzare 'stringa' in' bitset', dopo aver rimosso due primi segni di 'stringa'. – proton

Problemi correlati