How many bits are '1' in an integer variable?
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"
Could you know any other more efficient way?
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++ ;
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".