What does the bitwise AND operator & do?

╄→гoц情女王★ 提交于 2019-12-31 01:59:09

问题


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);
}

回答1:


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);



回答2:


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.




回答3:


& 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.




回答4:


you have count uninitialized

should be

static int count=0;

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



来源:https://stackoverflow.com/questions/5192238/what-does-the-bitwise-and-operator-do

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