BIT Counting: C programming problem
Jim Becker
jim at athsys.uucp
Tue Jan 10 09:11:02 AEST 1989
I was recently asked a problem to which there are a number of
solutions, I'm looking for opinions as to the best of those different
solutions.
The problem is the most efficient method to simply count the
number of on bits in a sixteen bit short. This is a really easy
exercise, but one that has a variety of different approaches. I would
be interested in the opinions of programmers out there, an efficient
algorithm that is understandable.
Assume that this is a basic sample algorithm:
int
BitCount( num )
short num;
{
int count = 0;
while( num ) {
count += (num & 1);
num = (num >> 1);
}
return count;
}
Is this efficient? Is this understandable? What is a better
algorithm? Please email your responses. I'll report the results of
algorithms when the votes are in. Thanx!
-Jim Becker ...!sun!athsys!jim
More information about the Comp.lang.c
mailing list