count of bits set in a long
Richard A. O'Keefe
ok at goanna.cs.rmit.oz.au
Tue Sep 25 14:16:28 AEST 1990
In article <37545 at ut-emx.uucp>, nwagner at ut-emx.uucp (Neal R. Wagner) writes:
> I need a fast method to count the number of bits that are set in a 32-bit
A simple way is to set up a table:
static char n_bits_set[256] = {0, 1, 1, 2, ... };
int bit_count(n)
unsigned long int n;
{
return n_bits_set[(n >> 24) ]
+ n_bits_set[(n >> 16) & 255]
+ n_bits_set[(n >> 8) & 255]
+ n_bits_set[(n ) & 255];
}
There's a rather nice loop that does one iteration per bit, and works
for any size, but I'll leave that for others.
--
Heuer's Law: Any feature is a bug unless it can be turned off.
More information about the Comp.lang.c
mailing list