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(final int targetSize)
next Power Of Two
return nextPowerOfTwo(1, targetSize);
longnextPowerOfTwo(final long nValue)
Return the least power of two greater than or equal to the specified value.
if (nValue == 0)
    return 1;
long x = nValue - 1;
x |= x >> 1;
x |= x >> 2;
x |= x >> 4;
x |= x >> 8;
x |= x >> 16;
...
intnextPowerOfTwo(int i)
next Power Of Two
String binary = Long.toBinaryString(i);
int power = binary.length() - binary.indexOf("1");
return (int) Math.pow(2, power);
intnextPowerOfTwo(int i)
next Power Of Two
i -= 1;
i |= (i >> 1);
i |= (i >> 2);
i |= (i >> 4);
i |= (i >> 8);
i |= (i >> 16);
return i + 1;
intnextPowerOfTwo(int i)
next Power Of Two
int minusOne = i - 1;
minusOne |= minusOne >> 1;
minusOne |= minusOne >> 2;
minusOne |= minusOne >> 4;
minusOne |= minusOne >> 8;
minusOne |= minusOne >> 16;
return minusOne + 1;
intnextPowerOfTwo(int n)
next Power Of Two
n = n - 1;
n = n | (n >> 1);
n = n | (n >> 2);
n = n | (n >> 4);
n = n | (n >> 8);
n = n | (n >> 16);
n = n + 1;
return n;
...
intnextPowerOfTwo(int num)
next Power Of Two
int result = 1;
while (num != 0) {
    num >>= 1;
    result <<= 1;
return result;
intnextPowerOfTwo(int value)
next Power Of Two
return 1 << (32 - Integer.numberOfLeadingZeros(value - 1));
intnextPowerOfTwo(int value)
Rounds the specified value up to the next nearest power of two.
return (int) Math.pow(2, Math.ceil(Math.log(value) / Math.log(2)));
intnextPowerOfTwo(int value)
Returns the smallest power-of-two that is greater than or equal to the supplied (positive) value.
return (Integer.bitCount(value) > 1) ? (Integer.highestOneBit(value) << 1) : value;