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?
Logical AND is not addition.
Specifically,
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:
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.
Output: