Skip to content

Commit

Permalink
Fast implementation of Hamming weight
Browse files Browse the repository at this point in the history
The target method: System.Reflection.Internal.BitArithmetic.CountBits
Old implementation uses 24 arithmetic operations
New fast implementation uses 12 arithmetic operations


Commit migrated from dotnet/corefx@f357187
  • Loading branch information
AndreyAkinshin committed Nov 25, 2014
1 parent c97e5f2 commit 62a8ee8
Showing 1 changed file with 7 additions and 16 deletions.
Expand Up @@ -7,22 +7,13 @@ internal static class BitArithmetic
{
internal static int CountBits(ulong v)
{
unchecked
{
const ulong MASK_01010101010101010101010101010101 = 0x5555555555555555UL;
const ulong MASK_00110011001100110011001100110011 = 0x3333333333333333UL;
const ulong MASK_00001111000011110000111100001111 = 0x0F0F0F0F0F0F0F0FUL;
const ulong MASK_00000000111111110000000011111111 = 0x00FF00FF00FF00FFUL;
const ulong MASK_00000000000000001111111111111111 = 0x0000FFFF0000FFFFUL;
const ulong MASK_11111111111111111111111111111111 = 0x00000000FFFFFFFFUL;
v = (v & MASK_01010101010101010101010101010101) + ((v >> 1) & MASK_01010101010101010101010101010101);
v = (v & MASK_00110011001100110011001100110011) + ((v >> 2) & MASK_00110011001100110011001100110011);
v = (v & MASK_00001111000011110000111100001111) + ((v >> 4) & MASK_00001111000011110000111100001111);
v = (v & MASK_00000000111111110000000011111111) + ((v >> 8) & MASK_00000000111111110000000011111111);
v = (v & MASK_00000000000000001111111111111111) + ((v >> 16) & MASK_00000000000000001111111111111111);
v = (v & MASK_11111111111111111111111111111111) + ((v >> 32) & MASK_11111111111111111111111111111111);
return (int)v;
}
const ulong Mask01010101 = 0x5555555555555555UL;
const ulong Mask00110011 = 0x3333333333333333UL;
const ulong Mask00001111 = 0x0F0F0F0F0F0F0F0FUL;
const ulong Mask00000001 = 0x0101010101010101UL;
v = v - ((v >> 1) & Mask01010101);
v = (v & Mask00110011) + ((v >> 2) & Mask00110011);
return (int)(unchecked(((v + (v >> 4)) & Mask00001111) * Mask00000001) >> 56);
}
}
}

0 comments on commit 62a8ee8

Please sign in to comment.