Path: utzoo!utgpu!news-server.csri.toronto.edu!rutgers!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!samsung!munnari.oz.au!csc.anu.oz.au!csc3.anu.oz.au!csc.canberra.edu.au!news From: eyal@moses.canberra.edu.au (Eyal Lebedinsky) Newsgroups: comp.lang.c Subject: Re: count of bits set in a long Keywords: bits set, count of, long Message-ID: <1990Sep25.085543.27563@csc.canberra.edu.au> Date: 25 Sep 90 08:55:43 GMT References: <37545@ut-emx.uucp> Sender: news@csc.canberra.edu.au Organization: none Lines: 22 In article <37545@ut-emx.uucp> nwagner@ut-emx.uucp (Neal R. Wagner) writes: > > 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. >[...program follows...] If speed if VERY important, try the bulk method: break the int into 4 bytes, have an array of 256 that holds the bit-count for any value from 0-255, and add the four counts. You can go dirty and redefine (union) the int because byte-ordering is not important. If the array is of type char then the indexing is very efficient. The program should DEFINITLY have no loops, just an addition of four array elements. -- Regards Eyal