Java Utililty Methods Bit Count

List of utility methods to do Bit Count

Description

The list of methods to do Bit Count are organized into topic(s).

Method

intcountBits(int x)
count Bits
x = (x & 0x55555555) + ((x >> 1) & 0x55555555);
x = (x & 0x33333333) + ((x >> 2) & 0x33333333);
x = (x & 0x0f0f0f0f) + ((x >> 4) & 0x0f0f0f0f);
x = (x & 0x00ff00ff) + ((x >> 8) & 0x00ff00ff);
x = (x & 0x0000ffff) + ((x >> 16) & 0x0000ffff);
return x;
bytecountBits(long num)
count 1 bits in nubmer.
byte result;
for (result = 0; Math.abs(num) > 0; result++) {
    num &= num - 1;
return result;
intcountBits(long value)
count Bits
int count = 0;
while (value > 0) {
    value >>= 1;
    count++;
return count;
intcountBitsInMask(int mask)
count Bits In Mask
switch (mask) {
case -1:
    return 32;
case 0:
    return 0;
case 1:
case 2:
case 4:
...
intcountBitsNeeded(int value)
Find out number of bits needed to represent a positive integer
return Integer.SIZE - Integer.numberOfLeadingZeros(value);
intcountBitsSet(int bitfield)
count Bits Set
int count = 0;
for (short i = 0; i < Integer.SIZE; i++) {
    if ((bitfield & 0x01) != 0) {
        count++;
    bitfield >>>= 1;
return count;
...