I'm looking for a very fast (hopefully 'fastest') function counting bits in a UIn64 (using C#). I read about a routine called 'Hackman 169' but can't find it.
What I do have is the routine for a UInt32 :
static ushort CountBits(UInt32 BitMask)
{ // Counting bits set for UInt32
UInt32 uCount = BitMask;
uCount = (uCount & 0x55555555) + (uCount >> 1 & 0x55555555);
uCount = (uCount & 0x33333333) + (uCount >> 2 & 0x33333333);
uCount = (uCount + (uCount >> 4)) & 0x0F0F0F0F;
uCount = uCount + (uCount >> 8);
uCount = (uCount + (uCount >> 16)) & 0x0000003F;
return (ushort) uCount;
}
I prefer a similar one for UInt64 .
Currently fastest rountine I found is:
static ushort CountBits(UInt64 BitMask)
{
ushort Count = 0;
while (BitMask != 0)
{
BitMask &= BitMask - 1;
Count++;
}
return Count;
}
The number of bits set in my UInt64 values vary from 0 to 8 so the function above will loop 1-9 times.


LinkBack URL
About LinkBacks