Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET equivalent of Java's Integer.bitCount?

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.

like image 848
finnw Avatar asked May 06 '11 10:05

finnw


3 Answers

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.

like image 121
Konrad Rudolph Avatar answered Nov 13 '22 06:11

Konrad Rudolph


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

  • PopCount(System.UInt32) and
  • PopCount(System.UInt64),

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.

like image 31
kbolino Avatar answered Nov 13 '22 05:11

kbolino


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;
}
like image 4
Daniel B Avatar answered Nov 13 '22 05:11

Daniel B