# Number of bits in a bitfield

This topic is 4410 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

Does anyone know of a fast way to count the number of bits in a bitfield (32 bit integer in my case)? Or at least be able to compare the number of bits in two bitfields?

##### Share on other sites
Im not sure what you mean, something like comparing these?

1110 0110 0101 0100 0101 010 1001 1010 1000

and

1110 0110 0101 0100 0101 010 1001 1010 1000

?

jsut compare their integer values?

##### Share on other sites
Do you mean the number of bits that are set, like bitCount(10010101) = 4 ?
If that is so, you could do like:

int bitCount(int bits){    int count;    for (count = 0 ; bits != 0 ; bits >>= 1)        count += (bits & 0x1);    return count;}

##### Share on other sites
A fast way would be a lookuptable for maybe a byte at a time. Storing 256 values doesn't take much space and retrieving the four bytes in your 32-bit integer one by one with masking is trivial too.
I have no good idea for generating the lookuptable though except typing it all on your own, which shouldn't be too much of a bother either.

##### Share on other sites
See the "Counting bits set" functions here.

1. 1
2. 2
Rutin
17
3. 3
4. 4
5. 5

• 13
• 26
• 10
• 11
• 9
• ### Forum Statistics

• Total Topics
633735
• Total Posts
3013595
×