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

家住魔仙堡 提交于 2019-12-10 02:46:53

问题


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.


回答1:


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 );


来源:https://stackoverflow.com/questions/11068204/is-it-possible-to-convert-bitset8-to-char-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!