Number of bits in a bitfield

Started by
3 comments, last by bakery2k1 17 years, 5 months ago
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?
Advertisement
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?
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;}

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.
See the "Counting bits set" functions here.

This topic is closed to new replies.

Advertisement