5

I am not sure how to translate this from C++ to Java. It is a function that computes the Hamming weight.

/** This is popcount_3() from:
 * http://en.wikipedia.org/wiki/Hamming_weight */
unsigned int popcnt32(uint32_t n) const
{
    n -= ((n >> 1) & 0x55555555);
    n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
    return (((n + (n >> 4))& 0xF0F0F0F)* 0x1010101) >> 24;
}

More concretely, I don't know what to use instead of uint32_t, and if I use that type whatever it is, can I just leave the rest code unchanged?

Thanks

user1796942
  • 3,228
  • 5
  • 29
  • 38

1 Answers1

18

It's implemented for you in Integer.bitCount(int i)

Alex D
  • 29,755
  • 7
  • 80
  • 126
zch
  • 14,931
  • 2
  • 41
  • 49