Tuesday, 11 October 2016

How to count the number of ones in a byte without a loop in c?





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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...