finding the number of SET bits in one line of code

Started by
21 comments, last by Enigma 18 years, 1 month ago
Quote:Original post by Anonymous Poster
Indeed, the fastest method is via a look-up table.
The fastest method is that assembly instruction that counts the number of set bits in a 32-bit value. No idea what it's called though...
Advertisement
Quote:Original post by Evil Steve
The fastest method is that assembly instruction that counts the number of set bits in a 32-bit value. No idea what it's called though...


You are thinking of BSR which computes the integer log base 2. I don't know of an instruction which counts the number of set bits.
"Debugging is twice as hard as writing the code in the first place. Therefore, if you write the code as cleverly as possible, you are, by definition, not smart enough to debug it." — Brian W. Kernighan
Based on the 64-bit versions on the page linked to by jpetrie and assuming an 8-bit byte and 32-bit unsigned int:
int countbits(unsigned int v){	return (((v * 0x01008040U) | (v >> 3)) & 0x11111111U) % 15;}

Σnigma

This topic is closed to new replies.

Advertisement