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

intnextPower(int v, int power)
next Power
int result = 1;
while (result < v) {
    result *= power;
return result;
intnextPower2(int n)
Returns the smallest power of 2 that is greater than the given integer.
if (n <= 0)
    return 1;
n--;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
...
intnextPowerOf2(final int n)
Returns the next power of 2 superior to n.
return (int) Math.pow(2, 32 - Integer.numberOfLeadingZeros(n - 1));
intnextPowerOf2(int n)
Returns the next power of 2 >= n.
if (n == 0) {
    return 1;
int b = Integer.highestOneBit(n);
return b == n ? n : b << 1;
intnextPowerOf2(int n)
Returns the next power of 2 that is greater or equal to the specified value.
assert n > 0;
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
return n + 1;
...
intnextPowerOf2(int n)
Returns the next bigger number that's a power of 2.
int exp;
exp = (int) StrictMath.ceil(StrictMath.log(n) / StrictMath.log(2.0));
exp = StrictMath.max(2, exp);
return (int) StrictMath.pow(2, exp);
intnextPowerOf2(int n)
Returns the nearest power of 2, which is either n if n is already a power of 2, or the next higher number than n which is a power of 2.
int x = 1;
while (x < n) {
    x <<= 1;
return x;
intnextPowerOf2(int v)
next Power Of
v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;
return v;
...
intnextPowerOf2(int x)
Get the value that is equal or higher than this value, and that is a power of two.
long i = 1;
while (i < x && i < (Integer.MAX_VALUE / 2)) {
    i += i;
return (int) i;
intnextPowerOf2(int x)
next Power Of
return 1 << (x == 0 ? 0 : 32 - Integer.numberOfLeadingZeros(x - 1));