What does the bitwise AND operator do?

Please help solve this problem and explain the logic. I do not know how the operator works here.

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

If you mean

a&=a-1;

then this is bitwise and operation a and a-1, copied subsequently.

Edit: As copied from Tadeusz A. Kadlubowski in the comment:

a = a & (a-1);
+5
source

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

Beginning with

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

Code output 32in 32-bit integer configuration.

+3
source

& .

a&=a-1;

:

a = a & a-1;

a.

, , a.

And since it is countdeclared as static, it is automatically initialized to 0.

+2
source

you consider uninitialized

it should be

static int count=0;

and called AND http://en.wikipedia.org/wiki/Bitwise_operation#AND

0
source

Source: https://habr.com/ru/post/1796253/


All Articles