count of bits set in a long
Bill Parke
parke at star.enet.dec.com
Wed Sep 26 06:35:06 AEST 1990
In article <661 at atcmpe.atcmp.nl>, jc at atcmp.nl (Jan Christiaan van Winkel)
writes:
|> From: jc at atcmp.nl (Jan Christiaan van Winkel)
|> Newsgroups: comp.lang.c
|> Subject: Re: count of bits set in a long
|>
|> 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
|> __/ \__/
____________________________________________________________________
|>
Actually I like:
int bitcount(int i)
{
register int c = 0 ;
while(i) {
i &= (i-1) ;
c++ ;
}
return c ;
}
Better.
--
Bill Parke parke%star.enet.dec at decwrl.dec.com
VMS Development decwrl!star.enet.dec.com!parke
Digital Equipment Corp parke at star.enet.dec.com
110 Spit Brook Road ZK01-1/F22, Nashua NH 03063
The views expressed are my own.
More information about the Comp.lang.c
mailing list