.NET equivalent of Java's Integer.bitCount?

4k Views Asked by At

Is there a method similar to Java's Integer.bitCount(int) or Long.bitCount(long) anywhere in the .NET Framework?

(For those unfamiliar with these Java methods) this is also known as:

  • Hamming Weight
  • Population Count (often called POPCNT when implemented in hardware.)

Although there are plenty of implementations to be found on the web, I was wondering if there was a standard library implementation.

I know this is not in BitArray, UInt32 or BitConverter, but maybe there's a version hidden somewhere, e.g. in a crypto function.

4

There are 4 best solutions below

4
On BEST ANSWER

Neither the BitVector32 nor the BitArray classes have such a method either so I believe that this method is indeed missing from the framework.

Personally, I think these classes aren’t really useful anyway since they miss many natural bit operations. I’m not sure what they are really intended for. As it is, their usefulness very limited.

2
On

These methods are based on algorithms from Hacker's Delight. You can download C code for them here.

0
On

This functionality is not in .NET Framework nor .NET Standard but it is in .NET Core 3.0 and newer, thus including .NET 5.0 and newer, under the System.Numerics.BitOperations static class, in particular the methods

both of which return System.Int32 aka int in C#.

There are also other useful operations: count leading or trailing zeros, compute integer base-2 logarithm, and perform bit rotation aka circular shift.

Possibly the biggest benefit of/reason for doing this in the core libraries is that you can get hardware acceleration without linking to unmanaged code, and the class docs confirm this:

Provides utility methods for intrinsic bit-twiddling operations. The methods use hardware intrinsics when available on the underlying platform; otherwise, they use optimized software fallbacks.

0
On

I know it's a very old question but it might be helpful for someone like me to have at least a workaround for this:

public static int BitCount(int n)
{
    var count = 0;
    while (n != 0)
    {
        count++;
        n &= (n - 1); //walking through all the bits which are set to one
    }

    return count;
}