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.
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 );
The provided solution did not worked for me. I was using C++14 with g++ 9. However, I was able to get it by :
char lower = 'a';
bitset<8> upper(lower);
upper.reset(5);
cout << (char)upper.to_ulong() << endl;
This may not be the best way to do it, I am sure, but it worked for me!