What does the bitwise AND operator & do in this code snippet?

1.8k views Asked by At

Please help to solve this problem and explain the logic. I don't know how the & operator is working here.

void main() {
   int a = -1;
   static int count;
   while (a) {
      count++;
      a &= a - 1;
   }
   printf("%d", count);
}
4

There are 4 answers

4
Tobias Wärre On

If you are referring to

a&=a-1;

then it is a bitwise and operation of a and a-1 copied into a afterwards.

Edit: As copied from Tadeusz A. Kadłubowski in the comment:

a = a & (a-1);
0
codaddict On

& is the bitwise and operator.

The operation

a&=a-1;

which is same as:

a = a & a-1;

clears the least significant bit of a.

So your program effectively is calculating the number of bits set in a.

And since count is declared as static it will automatically initialized to 0.

2
fazo On

you have count uninitialized

should be

static int count=0;

operator & is called AND http://en.wikipedia.org/wiki/Bitwise_operation#AND

0
Tugrul Ates On

The expression a&=a-1; clears the least significant bit (rightmost 1) of a. The code counts the number of bits in a (-1 in this case).

Starting from

a = -1 ; // 11111111 11111111 11111111 11111111 32bits signed integer

The code outputs 32 on an 32 bit integer configuration.