Write a function that returns the number of bits that are “on” (set to 1) in a byte. How can you make this function as fast as possible?
int countBits(unsigned char aByte)
{
{
Write a function that returns the number of bits that are “on” (set to 1) in a byte. How can you make this function as fast as possible?
1 Comment so far
Leave a comment
The idea is to bit-and with n-1. Every time this is done, the ’1′ on the LSB becomes 0.
Do this till the whole number becomes 0.
int count = 0;
while (n) { n = n&(n-1); count ++ }
return count;
By Nix on 09.29.09 1:23 pm | Permalink
Leave a comment
If you are including code in your comment, place it within a <div class='code'></div> tag for better formatting.