为什么std :: bitset< 8>变量无法处理11111111? [英] Why is the std::bitset<8> variable unable to handle 11111111?

查看:201
本文介绍了为什么std :: bitset< 8>变量无法处理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 1111111110 is 1010100110001010110001112. Upon construction, std::bitset<8> takes the eight least significant bits of that: 110001112.

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

One way to represent a bitset with a value of 111111112 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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆