count of bits set in a long
Neal R. Wagner
nwagner at ut-emx.uucp
Tue Sep 25 08:37:26 AEST 1990
I need a fast method to count the number of bits that are set in a 32-bit
integer on a Sun 3/80 running 4.0.3 SunOS. The brute-force method follows.
Is there a faster way in C? How close in speed to a hand-coded assembly
routine would a fast method in C be (after the latter is run through the
optimizer)?
Thanks in advance for your help. Send e-mail and I will summarize for the
net.
===============================================================================
#define BIT_SETSIZE 32
typedef unsigned long bit_set;
#define BIT_ISSET(bit,bitset) (((bitset) & (1<<(bit))) >> (bit))
int bit_count();
main()
{
bit_set i;
for (i=0; i<=16; i++)
printf("%d has %d bits on\n", i, bit_count(i));
}
intint bit_count(i)
bit_set i;
{
int j, k;
k = 0;
for (j=0; j<BIT_SETSIZE; j++) k = k + BIT_ISSET(j, i);
return k;
}
===============================================================================
More information about the Comp.lang.c
mailing list