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

intbitLength(int value)
bit Length
return Integer.SIZE - Integer.numberOfLeadingZeros(value);
intbitSizeForSignedValue(final int value)
bit Size For Signed Value
if (value > 0) {
    return 33 - Integer.numberOfLeadingZeros(value);
} else if (value == 0) {
    return 1;
} else {
    return 33 - Integer.numberOfLeadingZeros(-value - 1);
intbitSizeForUnsignedValue(final int value)
bit Size For Unsigned Value
if (value > 0) {
    return 32 - Integer.numberOfLeadingZeros(value);
} else {
    if (value == 0) {
        return 1;
    } else {
        throw new IllegalArgumentException("unsigned value [" + value + "] must be >= 0");
intcountBits(long v)
count Bits
int count = 0;
for (; v > 0; v = v / 2) {
    ++count;
return count;
intcountBits(byte num)
count Bits
int count = 0;
for (int i = 0; i < 8; i++) {
    if ((num & 1) == 1) 
        count++;
    num = (byte) (num >>> 1); 
return count;
intcountBits(final int intValue)
Counts the number of 1-Bits in a 32-bit int value and uses a "divide-and-conquer" strategy.
final byte const16 = 16;
final byte const3F = 0x0000003F;
final int const33 = 0x33333333;
final int const55 = 0x55555555;
final int const0F = 0x0F0F0F0F;
int result = intValue;
result -= ((result >>> 1) & const55);
result = (result & const33) + ((result >>> 2) & const33);
...
intcountBits(int i)
Count the number of non-zero bits of a integer
i = (((i & 0xAAAAAAAA) >>> 1) + (i & 0x55555555));
i = (((i & 0xCCCCCCCC) >>> 2) + (i & 0x33333333));
i = (((i & 0xF0F0F0F0) >>> 4) + (i & 0x0F0F0F0F));
i = (((i & 0xFF00FF00) >>> 8) + (i & 0x00FF00FF));
i = (((i & 0xFFFF0000) >>> 16) + (i & 0x0000FFFF));
return i;
intcountBits(int mask)
count Bits
int count = 0;
for (int index = 0; index < 32; index++) {
    if ((mask & 0x1) != 0) {
        count++;
    mask = mask >>> 1;
return count;
...
intcountBits(int n)
A magic utility method that happens to return the number of bits that are set to '1' in the given number.
int m = n - ((n >> 1) & 033333333333) - ((n >> 2) & 011111111111);
return ((m + (m >> 3)) & 030707070707) % 63;
intcountBits(int x)
Count the bits in an int
int n = 0;
while (x != 0) {
    if ((x & 1) != 0)
        n++;
    x >>>= 1;
return n;