Sim
Sim

Reputation: 4184

bitsets binary AND operation

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?

Upvotes: 4

Views: 3493

Answers (2)

Peter Alexander
Peter Alexander

Reputation: 54270

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

Upvotes: 6

sll
sll

Reputation: 62504

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?

Upvotes: 0

Related Questions