diff --git a/src/Microsoft.AspNet.Server.Kestrel/Infrastructure/LongExtensions.cs b/src/Microsoft.AspNet.Server.Kestrel/Infrastructure/LongExtensions.cs index 0ac6a718d4..3b79425172 100644 --- a/src/Microsoft.AspNet.Server.Kestrel/Infrastructure/LongExtensions.cs +++ b/src/Microsoft.AspNet.Server.Kestrel/Infrastructure/LongExtensions.cs @@ -7,12 +7,18 @@ namespace Microsoft.AspNet.Server.Kestrel.Extensions { public static int BitCount(this long value) { - // Parallel bit count for a 64-bit integer + // see https://github.com/dotnet/corefx/blob/master/src/System.Reflection.Metadata/src/System/Reflection/Internal/Utilities/BitArithmetic.cs + + const ulong Mask01010101 = 0x5555555555555555UL; + const ulong Mask00110011 = 0x3333333333333333UL; + const ulong Mask00001111 = 0x0F0F0F0F0F0F0F0FUL; + const ulong Mask00000001 = 0x0101010101010101UL; + var v = (ulong)value; - v = v - ((v >> 1) & 0x5555555555555555); - v = (v & 0x3333333333333333) + ((v >> 2) & 0x3333333333333333); - v = (v + (v >> 4) & 0x0f0f0f0f0f0f0f0f); - return (int)((v * 0x0101010101010101) >> 56); + + v = v - ((v >> 1) & Mask01010101); + v = (v & Mask00110011) + ((v >> 2) & Mask00110011); + return (int)(unchecked(((v + (v >> 4)) & Mask00001111) * Mask00000001) >> 56); } } }