# Thread: What does this statement do ?

1. ## What does this statement do ?

The program main call a func that just counts the binary 1 in an 8 bit number. Please see line in RED below.

I do not know how result is incremented based on the highlighted line. I looked through my C programming book and could not find anything that describes the statement. It does work however.

Code:
```int i=1, myInt;

int main(int argc, char *argv[]) {

i=37; //"00100101" in binary, contains three bits that are set to "1".
myInt=count_ones(i);
printf("%d\r\n",myInt);
}
//A simple example of C code, designed to count the 1 bits in a int, might look like this:

int count_ones(unsigned int x) {
int result = 0;
while (x != 0)
result++, x = x & (x-1);
return result;
}``` 2. Every time you do this x=x&(x-1) it sets the rightmost 1-bit to 0.
Code:
```x        00100101
x-1      00100100
x&(x-1)  00100100     rightmost bit gone

x        00100100
x-1      00100011
x&(x-1)  00100000     rightmost bit gone

x        00100000
x-1      00011111
x&(x-1)  00000000     now x is 0, so we're done```
Subtracting 1 from a number sets it's rightmost 1-bit to 0 and any 0 bits to the right of it to 1's. The "bitwise and" masks the extra 1's against the 0's in the original number.

Your variables don't need to be global.
You should have the function prototype above main.
You should generally avoid using the comma operator to avoid braces.
You probably don't need to print the '\r' character. 3. Registered User
Join Date Jul 2002
Posts 1

Now that's some quality lurking  4. Hi John, thanks for taking the time to answer my question. I see what's happening now. Isn't there supposed to be a semicolon after result++ ?
That is what i don't understand. But the C compiler that I am using takes it fine. 5. Originally Posted by Salem Registered User
Join Date Jul 2002
Posts 1

Now that's some quality lurking Wow, is that when I signed up ? I haven't been lurking but I should of been. I must of been on the Arduino forum 6. The comma operator makes it a single statement, so you can get away without using braces in the while loop.

This is the same, only better.
Code:
```while (x != 0){
result++;
x = x & (x-1);
}```
You can now add say a printf to examine variables without having to completely restructure the code. 7. Ok, thanks Salem Popular pages Recent additions binary, bits, int, result, statement 