count of bits set in a long

Mark Dawson md at doc.ic.ac.uk
Tue Sep 25 21:07:51 AEST 1990


In <3820 at goanna.cs.rmit.oz.au> ok at goanna.cs.rmit.oz.au (Richard A. O'Keefe) writes:
>There's a rather nice loop that does one iteration per bit, and works
>for any size ...

Here it is:

	num_set_bits = 0;
	while (word != 0) { /* there must be at least one bit set */
		num_set_bits++;
		word &= (word - 1); /* remove the least significant set bit */
		/* iterate... */
	}

Mark



More information about the Comp.lang.c mailing list