How many bits are '1' in an integer variable?

Hi folks,

I am trying to find a more efficient way to count "How many bits are

'1' in an integer variable?".

I still have no idea to count the bits except using a loop and "if"

statements.

Could you know any other more efficient way?

Cuthbert

Code:

`int main (void)`

{

int var = 0xFF0F;

int i, count = 0;

int mask = 1;

for ( i = 0; i < sizeof(int)*8 ; i++ )

if ( mask<<i & var) count++ ;

printf("%d\n", count);

return 0;

}

I'm glad to see you're using hex!

**I'm glad to see you're using hex!** I always recommend hex when working with binary numbers & bitwise operations. Even if the 'assignment' doesn't required it, displaying the variable in hex makes it much easier to "see" what your program is doing.

Once you understand the relationship between hex and binary, you can look at 0xFF0F and instantly see that there are 12 "ones".