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

2020-08-26 05:41发布

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.

标签: c++ char bitset
2条回答
仙女界的扛把子
2楼-- · 2020-08-26 05:48
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 );
查看更多
ら.Afraid
3楼-- · 2020-08-26 05:50

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!

查看更多
登录 后发表回答