Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!usc!srhqla!demott!kdq From: kdq@demott.COM (Kevin D. Quitt) Newsgroups: comp.lang.c Subject: Re: count of bits set in a long Keywords: bits set, count of, long Message-ID: <644@demott.COM> Date: 2 Oct 90 21:38:16 GMT References: <12330@crdgw1.crd.ge.com> Reply-To: kdq@demott.COM (Kevin D. Quitt) Organization: DeMott Electronics Co., Van Nuys CA Lines: 27 In article <12330@crdgw1.crd.ge.com> davidsen@antarctica.crd.GE.COM (william E Davidsen) writes: > > There have been lots of fast but non-portable solutions posted. > > I like the one which said (paraphrase) > > while (n) { > count += (n & 1); > n >>= 1; > } This one, of course, assumes that the shift is logical, not arithmetic, or your first negative number will keep you occupied for quite a while. I think the best solution is: char *ptr = (char *)&lvar; int count = 0; for ( i = 0; i < sizeof( long ); i++ ) count += bits_in_byte[ *p++ ]; -- _ Kevin D. Quitt demott!kdq kdq@demott.com DeMott Electronics Co. 14707 Keswick St. Van Nuys, CA 91405-1266 VOICE (818) 988-4975 FAX (818) 997-1190 MODEM (818) 997-4496 PEP last 96.37% of all statistics are made up.