Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!know!zaphod.mps.ohio-state.edu!uakari.primate.wisc.edu!aplcen!haven!decuac!shlump.nac.dec.com!star.enet.dec.com!parke From: parke@star.enet.dec.com (Bill Parke) Newsgroups: comp.lang.c Subject: Re: count of bits set in a long Message-ID: <1990Sep25.163315@star.enet.dec.com> Date: 25 Sep 90 20:35:06 GMT References: <661@atcmpe.atcmp.nl> <37545@ut-emx.uucp> Sender: newsdaemon@shlump.nac.dec.com Reply-To: parke@star.enet.dec.com (Bill Parke) Organization: Digital Equipment Corporation, Nashua NH Lines: 53 In article <661@atcmpe.atcmp.nl>, jc@atcmp.nl (Jan Christiaan van Winkel) writes: |> From: jc@atcmp.nl (Jan Christiaan van Winkel) |> Newsgroups: comp.lang.c |> Subject: Re: count of bits set in a long |> |> From article <37545@ut-emx.uucp>, by nwagner@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@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@decwrl.dec.com VMS Development decwrl!star.enet.dec.com!parke Digital Equipment Corp parke@star.enet.dec.com 110 Spit Brook Road ZK01-1/F22, Nashua NH 03063 The views expressed are my own.