Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to convert bitset<8> to char in c++?

Tags:

c++

char

bitset

I have bitset<8> v8 and its value is something like "11001101", how can I convert it to char? I need a single letter. Like letter "f"=01100110.

P.S. Thanks for help. I needed this to illustrate random errors in bits. For example without error f, and with error something like ♥, and so on with all text in file. In text you can see such errors clearly.

like image 686
Van Avatar asked Jun 17 '12 01:06

Van


1 Answers

unsigned long i = mybits.to_ulong(); 
unsigned char c = static_cast<unsigned char>( i ); // simplest -- no checks for 8 bit bitsets

Something along the lines of the above should work. Note that the bit field may contain a value that cannot be represented using a plain char (it is implementation defined whether it is signed or not) -- so you should always check before casting.

char c;
if (i <= CHAR_MAX) 
c = static_cast<char>( i );
like image 150
dirkgently Avatar answered Oct 02 '22 13:10

dirkgently