Java Utililty Methods Power of 2

List of utility methods to do Power of 2

Description

The list of methods to do Power of 2 are organized into topic(s).

Method

intnextPowerOfTwo(int value)
next Power Of Two
if (value == 0)
    return 1;
if ((value & value - 1) == 0)
    return value;
value |= value >> 1;
value |= value >> 2;
value |= value >> 4;
value |= value >> 8;
...
intnextPowerOfTwo(int x)
Calculates an integer that is a power of two and is equal or greater than a given integer
int y;
for (y = 1; y < x; y <<= 1)
    ;
return y;
intnextPowerOfTwo(int x)
Return the least power of two greater than or equal to the specified value.
if (x == 0)
    return 1;
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
return (x | x >> 16) + 1;
...
intnextPowerOfTwo(int x)
next Power Of Two
if ((x & (x - 1)) != 0)
    x = Integer.highestOneBit(x) * 2;
if ((x & (x - 1)) != 0)
    throw new RuntimeException("Error in nextPowerOfTwo");
return x;
intnextPowerOfTwo(int x)
next Power Of Two
if (x == 0) {
    return 1;
} else {
    --x;
    x |= x >> 1;
    x |= x >> 2;
    x |= x >> 4;
    x |= x >> 8;
...
intnextPowerOfTwo(int x)
Next Largest Power of 2: Given a binary integer value x, the next largest power of 2 can be computed by a SWAR algorithm that recursively "folds" the upper bits into the lower bits.
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
intnextPowerOfTwo(int x)
Returns the next largest power of two, or zero if x is already a power of two.
assert x < 0x10000;
int bit = 0x8000, highest = -1, count = 0;
for (int i = 15; i >= 0; --i, bit >>= 1) {
    if ((x & bit) != 0) {
        ++count;
        if (highest == -1) {
            highest = i;
if (count <= 1) {
    return 0;
return 1 << (highest + 1);
intnextPowerOfTwo(int x)
Calculate the next power of 2, greater than or equal to x.

From Hacker's Delight, Chapter 3, Harry S.

assert x > 0;
x |= --x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
return x + 1;
intnextPowerOfTwo(int x)
Calculate the next power of 2.
x--;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
x++;
return x;
...
intnextPowerOfTwo(int x)
Throws IllegalArgumentException if x is negative
if (x < 0)
    throw new IllegalArgumentException("Argument is negative: " + x);
if (x == 0)
    return 1;
x--;
x |= (x >> 1);
x |= (x >> 2);
x |= (x >> 4);
...