可以将bitset< 8>到c ++中的char? [英] Is it possible to convert bitset<8> to char in c++?
问题描述
我有bitset< 8> v8,它的值是类似11001101,我怎么转换成char?我需要一封信。喜欢字母f= 01100110。
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.
感谢帮助。我需要这个来说明位的随机错误。例如没有错误f,有错误的东西像♥,等等与文件中的所有文本。在文本中,您可以清楚地看到此类错误。
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
请注意,位字段可能包含无法使用简单 char
(它是实现定义是否已签名)表示的值 - 因此您应该总是先检查
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 );
这篇关于可以将bitset< 8>到c ++中的char?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!