Explanation of while(m)m&=m-1,s++;

Words: 477

This post is a supplement to 【NYOJ】[100] Number of 1s.
The reference solution for this problem uses this line of code, which is rather hard to understand.

So let’s break it down

Comma operator

while(m)m&=m-1,s++; can be written as:

1
2
while(m)
	m&=m-1,s++;

First, what the “,” stands for.
Here it acts as the comma operator.
About the comma operator:

The comma operator can join two or more (at least two) expressions into a single expression, which is called a comma expression.

The comma operator has the lowest precedence of all operators, and is usually used together with for loops.

So the common for(i=0,n=1;i<10;i++)
pattern: this i=0,n=1 is a comma expression.

For the expression a + b, c = b, c++

The value of the rightmost subexpression is the value of the comma expression. In the example above, the value of c++ (the value of c before the increment) is the value of that expression.

The comma operator guarantees that the left subexpression is fully evaluated before the right subexpression is evaluated. In other words, the comma operator is a sequence point: only after all side effects on its left are complete does evaluation of the right subexpression begin. Therefore, in the example above, c is incremented only after it has received the value of b.

Verification program:

1
2
3
4
5
6
7
8
9
#include<stdio.h>
int main() {
	int x,a;
	x=(a=3,6*3);
	printf("a=%d,x=%d\n",a,x);
	x=a=3,6*a;
	printf("a=%d,x=%d\n",a,x);
	return 0;
}

So while(m)m&=m-1,s++; can be seen as two loop statements

1
2
m&=m-1;
s++;

Bitwise operations

s++ is easy to understand.
So how should m&=m-1; be explained?

Here & is bitwise AND.
That is, for each bit of the binary numbers, the result bit is 1 only if both numbers have 1 in that bit.

A common idiom:
if(a&1) is equivalent to asking whether a is odd.
Because if a is odd, its last bit is 1,
so a&1 is also 1.
If a is even, then a&1==0.

Here m&=m-1 =>m=m&m-1
Why does writing it this way count the number of 1s?

Example
5 in binary is 101
The computation goes:
100&101==100 =>s==1
100&011==0 =>s==2

Analysis
m&m-1 works like this: if the last bit is 1,
then the result is as if the last 1 were removed and the count incremented by 1.
If the last bit is 0,
then the preceding 1 bit becomes 0 after the operation and the count is incremented by 1,
while that bit itself stays 0.

So in this way, one 1 bit at a time is flipped to 0,
and the number of times is recorded,
which yields how many 1s the number has in binary.

It is also a fascinating manifestation of binary arithmetic.

References:
《C Programming Language — Jia Zongpu, Xu Heli》
Functions and usage of the comma operator in C _ Baidu Zhidao
Bitwise operations _ Baidu Baike

This post is licensed under CC BY-NC-SA 4.0. If it helped, or if you have anything to say, the comment box below is open.
Page views —
Unique visitors —

Loading...