为什么std :: bitset< 8>变量无法处理11111111? [英] Why is the std::bitset<8> variable unable to handle 11111111?
问题描述
为什么此程式显示下列输出?
#include< bitset>
...
{
std :: bitset< 8> b1(01100100); std :: cout << b1<< std :: endl;
std :: bitset< 8> b2(11111111); std :: cout<< b2<< std :: endl; //看,这个变量
//已经赋值
//值11111111
//,而在
//执行期间,它需要
// value 11000111
std :: cout<< b1& b2:< (b1& b2)< '\\\
';
std :: cout<< b1 | b2:< (b1 | b2)< '\\\
';
std :: cout<< b1 ^ b2:< (b1 ^ b2)< '\\\
';
}
这是OUTPUT:
01000000
11000111
b1& b2:01000000
b1 | b2:11000111
b1 ^ b2:10000111
首先,我认为头文件(我使用MinGW)所以我
使用MSVCC检查。但它也显示了同样的事情。请帮助。
除了外观, 11111111
11111111
10 的二进制表示为 101010011000101011000111
2 。在构造时, std :: bitset< 8>
采用八个最低有效位: 11000111
2
第一种情况是类似的,除了 01100100
是八进制(由于前导零) 。以二进制表示的相同数字是 1001000000001000000
2 。
值 11111111
2 的比特组是 std :: bitset< 8>或者,您可以从二进制字符串构造一个bitset:
std :: bitset< 8> b1(std :: string(01100100));
std :: bitset< 8> b2(std :: string(11111111));
Why is this program showing the following output ?
#include <bitset>
...
{
std::bitset<8> b1(01100100); std::cout<<b1<<std::endl;
std::bitset<8> b2(11111111); std::cout<<b2<<std::endl; //see, this variable
//has been assigned
//the value 11111111
//whereas, during
//execution, it takes
//the value 11000111
std::cout << "b1 & b2: " << (b1 & b2) << '\n';
std::cout << "b1 | b2: " << (b1 | b2) << '\n';
std::cout << "b1 ^ b2: " << (b1 ^ b2) << '\n';
}
This is the OUTPUT:
01000000
11000111
b1 & b2: 01000000
b1 | b2: 11000111
b1 ^ b2: 10000111
First, I thought there is something wrong with the header file (I was using MinGW) so I checked using MSVCC. But it too showed the same thing. Please help.
Despite the appearance, the 11111111
is decimal. The binary representation of 11111111
10 is 101010011000101011000111
2. Upon construction, std::bitset<8>
takes the eight least significant bits of that: 11000111
2.
The first case is similar except the 01100100
is octal (due to the leading zero). The same number expressed in binary is 1001000000001000000
2.
One way to represent a bitset with a value of 11111111
2 is std::bitset<8> b1(0xff)
.
Alternatively, you can construct a bitset from a binary string:
std::bitset<8> b1(std::string("01100100"));
std::bitset<8> b2(std::string("11111111"));
这篇关于为什么std :: bitset< 8>变量无法处理11111111?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!