# Thread: How many bits are '1' in an integer variable?

1. ## 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;
for ( i = 0; i < sizeof(int)*8 ; i++ )
if ( mask<<i & var) count++ ;

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

return 0;
}

2. >I am trying to find a more efficient way to...
Why do you need a more efficient way?

>Could you know any other more efficient way?
Yes, of course. Use a lookup table.

3. One change you could make to speed this up (just a very little bit) would be to change:
Code:
if (mask <<i & var) count++;
to
Code:
to get rid of the * in the code, which is longer than doing a bitwise shift.

4. >Could you know any other more efficient way?
Code:
int var = 0xFF0F;
printf("%d\n", (int) std::bitset<sizeof(int)*8>(var).count());

5. A non-portable way is to use itoa() if your compiler supports it, with a radix of 2. This will return a C-style string you can then count for 1s.

A portable way involves the use of recursion as seen here http://www.engin.umd.umich.edu/CIS/c...pp/binary.html, changing it where appropriate to count 1s.

Both options are faster than what you are doing.

EDIT: Well... swoopy's faster no doubt

6. >> sizeof(int)*8

7. Originally Posted by swoopy
>Could you know any other more efficient way?
Code:
int var = 0xFF0F;
printf("%d\n", (int) std::bitset<sizeof(int)*8>(var).count());
What won't compile for me!! (c++?)

8. ## 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".

9. >What won't compile for me!!
Maybe it's because you're using K&R C.

10. Originally Posted by Prelude
>What won't compile for me!!
Maybe it's because you're using K&R C.
I am using gcc.

11. The question was cross-posted to the C++ board, so presumably C++ answers are valid.

12. Originally Posted by Daved
>> sizeof(int)*8
Yes thanks, that's would be better.

13. Originally Posted by esbo
What won't compile for me!! (c++?)
Make sure you compile as C++ (.cpp file) and #include <bitset>

14. Originally Posted by swoopy
Make sure you compile as C++ (.cpp file) and #include <bitset>
Well as he posted in the C forum I presume he wanted to use C?

15. Originally Posted by esbo
Well as he posted in the C forum I presume he wanted to use C?
Well maybe Prelude will post one then. Hopefully without a lookup table though. That kind of takes the fun out of it.