bitsets binary AND operation

荒凉一梦 提交于 2019-12-23 12:45:45

问题


I wrote the following lines:

std::bitset<4> bitvec;  //bitset 0000
std::bitset<4> addition; //bitset 0000

addition.set(0); //setting the least significant bit

std::cout << addition << std::endl; //output 0001
std::cout << std::endl;

for(int x = 0; x != 16; ++x) { //addition loop
    std::cout << bitvec << std::endl; //output
    bitvec &= addition; //binary AND
}

std::cout << std::endl;

and I expected the output to be:

0000
0001
0010
0011
0100
0101
....

But the loop just outputs '0000'. What basic concept am I missing?


回答1:


Logical AND is not addition.

Specifically,

  0000
& 0001
------
= 0000

Which explains why you always get 0000.

Logical AND just looks at each bit in both bitsets and only outputs a 1 if that bit is 1 in both of the other vectors. As an example:

  1001
& 1100
------
= 1000

The reason that first bit is 1 is because the first bit in the other bitsets is 1. The rest are 0 because one of the bitsets has a 0 at that position.

If you want addition, don't use a bitset, and just use addition.

unsigned long a = 0;

for (int i = 0; i < 16; ++i)
{
    std::cout << std::bitset<4>(a) << std::endl;
    ++a;
}

Output:

0000
0001
0010
0011
0100
0101
0110
0111
1000
1001
1010
1011
1100
1101
1110
1111



回答2:


On the first loop cycle bitvec = 0000 addition = 0001

0000 AND 0001 operation will result as 0000 and you assign the 0000 to bitvec and history repeating on the all next loop cycles.

Your expected results is a result of simple increment operation or +1 addition, basically just prin x in binary format. What are you trying to do with bitwise AND?

  • Bitwise AND operation


来源:https://stackoverflow.com/questions/7783837/bitsets-binary-and-operation

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