Skip to content

Instantly share code, notes, and snippets.

@rcc
Last active September 4, 2015 20:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rcc/380967 to your computer and use it in GitHub Desktop.
Save rcc/380967 to your computer and use it in GitHub Desktop.
Log(N) method for calculating the number of bits set in a word
/* Log(N) method for calculating the number of bits set in a word */
uint8_t bits_set(uint32_t word)
{
word = (word & 0x55555555) + ((word >> 1) & 0x55555555);
word = (word & 0x33333333) + ((word >> 2) & 0x33333333);
word = (word & 0x0F0F0F0F) + ((word >> 4) & 0x0F0F0F0F);
word = (word & 0x00FF00FF) + ((word >> 8) & 0x00FF00FF);
word = (word & 0x0000FFFF) + ((word >> 16) & 0x0000FFFF);
return (uint8_t)word;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment