Jump to content
  • Advertisement
Sign in to follow this  
Axiverse

Number of bits in a bitfield

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
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?

Share this post


Link to post
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 this post


Link to post
Share on other sites
Guest Anonymous Poster
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 this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!