Possible Duplicate:
Best algorithm to count the number of set bits in a 32-bit integer?
Hello,
Is there a more compact way of counting the number of ones in a byte without using a loop? I don't want to do the following if I don't have to. Thanks.
char myValue = 0x0F;
int counter = 0;
while (myValue > 0)
{
if (myValue & 0x01)
{
counter ++;
}
myValue = myValue >> 1;
}
Answer
((i>>3)&1)+((i>>2)&1)+((i>>1)&1)+(i&1)
Or use assembly (SSE/MMX).
http://gurmeet.net/puzzles/fast-bit-counting-routines/
No comments:
Post a Comment