count of bits set in a long

Jan Christiaan van Winkel jc at atcmp.nl
Tue Sep 25 22:04:35 AEST 1990


>From article <37545 at ut-emx.uucp>, by nwagner at ut-emx.uucp (Neal R. Wagner):
> 
>   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.

How about:

int bit_count(i)
unsigned long i;
{
	int k=0;
	for (; i!=0; i>>=1) k += (i & 1);
	return k;
}
-- 
___  __  ____________________________________________________________________
   |/  \   Jan Christiaan van Winkel      Tel: +31 80 566880  jc at atcmp.nl
   |       AT Computing   P.O. Box 1428   6501 BK Nijmegen    The Netherlands
__/ \__/ ____________________________________________________________________



More information about the Comp.lang.c mailing list