count of bits set in a long

Kevin D. Quitt kdq at demott.COM
Wed Oct 3 07:38:16 AEST 1990


In article <12330 at crdgw1.crd.ge.com> davidsen at 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 at 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.



More information about the Comp.lang.c mailing list