Last active
September 4, 2015 20:44
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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