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:
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.
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.
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)
andPopCount(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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With