Why is the std::bitset<8> variable unable to handle 11111111?

青春壹個敷衍的年華 提交于 2019-12-05 01:03:59

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

As per NPE's answer, you are constructing the bitset with an unsigned long, and not with bits as you were expecting. An alternative way to construct it, which enables you to specify the bits, is by using the string constructor as follows:

#include <bitset>
#include <cstdio>
#include <iostream>

int main()
{
    std::bitset<8> b1(std::string("01100100")); std::cout<<b1<<std::endl;
    std::bitset<8> b2(std::string("11111111")); std::cout<<b2<<std::endl;
    std::cout << "b1 & b2: " << (b1 & b2) << '\n';
    std::cout << "b1 | b2: " << (b1 | b2) << '\n';
    std::cout << "b1 ^ b2: " << (b1 ^ b2) << '\n';
getchar();
return 0;
}

Click here to view the output.

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