Java Number Round roundToNextPowerOfTwo(int value)

Here you can find the source of roundToNextPowerOfTwo(int value)

Description

Returns the closest power of two for the given value.

License

Open Source License

Parameter

Parameter Description
value original input value

Return

the closest power of two for the given value

Declaration

public static int roundToNextPowerOfTwo(int value) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

public class Main {
    /**/*w ww  .j  av  a2s  .c  om*/
     * Returns the closest power of two for the given value.
     *
     * @param value original input value
     * @return the closest power of two for the given value
     */
    public static int roundToNextPowerOfTwo(int value) {
        if (value < 0) {
            throw new UnsupportedOperationException();
        }

        // Alternatively this works too but our implementation seems to be more
        // efficent in terms of CPU operations executed (numberOfLeadingZeros does
        // exactly this, plus other things). However, numberOfLeadingZeros will
        // return '1' for value=0 which is arguably more correct:
        //
        // return 1 << (32 - Integer.numberOfLeadingZeros(value - 1));

        value--;
        value |= value >>> 1;
        value |= value >>> 2;
        value |= value >>> 4;
        value |= value >>> 8;
        value |= value >>> 16;

        return ++value;
    }
}

Related

  1. roundToNearestMultiple(double number, double multiple)
  2. roundToNearestMultipleOf(final long num, final long multipleOf)
  3. roundToNearestN(float value, float n)
  4. roundToNearestPowerOfTen(double value)
  5. roundToNext(int val, int factor)
  6. roundToNthDecimal(double number, int decimals)
  7. roundToNumDigits(double d, int n)
  8. roundToPowerOf(int i, int powerOf)
  9. roundToPowerOf10(double value, int powerOf10)