Search code examples
java.netbit-manipulationhammingweight

.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.


Solution

  • 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.