本文介绍了为什么std :: bitset< 8>变量无法处理11111111?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么此程式显示下列输出?

  #include< bitset> 
...

{
std :: bitset< 8> b1(01100100); std :: cout 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 的二进制表示为 101010011000101011000111 。在构造时, std :: bitset< 8> 采用八个最低有效位: 11000111



11111111 的比特组是 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 Ichecked using MSVCC. But it too showed the same thing. Please help.

解决方案

Despite the appearance, the 11111111 is decimal. The binary representation of 11111111 is 101010011000101011000111. Upon construction, std::bitset<8> takes the eight least significant bits of that: 11000111.

The first case is similar except the 01100100 is octal (due to the leading zero). The same number expressed in binary is 1001000000001000000.

One way to represent a bitset with a value of 11111111 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&lt; 8&gt;变量无法处理11111111?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:48
查看更多