count of bits set in a long

Eyal Lebedinsky eyal at moses.canberra.edu.au
Tue Sep 25 18:55:43 AEST 1990


In article <37545 at ut-emx.uucp> nwagner at 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



More information about the Comp.lang.c mailing list