count of bits set in a long

william E Davidsen davidsen at antarctica.crd.GE.COM
Wed Oct 3 00:00:57 AEST 1990


  There have been lots of fast but non-portable solutions posted. I
think this problem lends itself to a non-portable solution for speed,
but please remember that if you assume (a) all longs have 32 bits or (b)
all computers have 2's complement arithmetic, or (c) all bytes are 8
bits...

                ** All the world's not a VAX (or Sun) **

and many of the solutions posted are not going to work.

  I like the one which said (paraphrase)

	while (n) {
	  count += (n & 1);
	  n >>= 1;
	}
-- 
Bill Davidsen (davidsen at crdos1.crd.ge.com, uunet!crdgw1!crdos1!davidsen)
  GE Corp R&D Center, Schenectady NY
  Moderator of comp.binaries.ibm.pc and 386users mailing list
       "This is your PC. This is your PC on OS/2. Any questions?"



More information about the Comp.lang.c mailing list