Java Power of 2 nextPowerOfTwo(int x)

Here you can find the source of nextPowerOfTwo(int x)

Description

Throws IllegalArgumentException if x is negative

License

Open Source License

Declaration

public static int nextPowerOfTwo(int x) 

Method Source Code

//package com.java2s;

public class Main {
    /**// w w w  . j a v a2s.c  o m
     * Throws {@link IllegalArgumentException} if x is negative
     */
    public static int nextPowerOfTwo(int x) {
        if (x < 0)
            throw new IllegalArgumentException("Argument is negative: " + x);
        if (x == 0)
            return 1;

        // Copy the highest set bit into all lower bits, then add
        // one -- but first, subtract one, so that it works if x
        // is already a power of two
        x--;
        x |= (x >> 1);
        x |= (x >> 2);
        x |= (x >> 4);
        x |= (x >> 8);
        x |= (x >> 16);
        x++;

        return x;
    }
}

Related

  1. nextPowerOfTwo(int num)
  2. nextPowerOfTwo(int value)
  3. nextPowerOfTwo(int value)
  4. nextPowerOfTwo(int value)
  5. nextPowerOfTwo(int value)
  6. nextPowerOfTwo(int x)
  7. nextPowerOfTwo(int x)
  8. nextPowerOfTwo(int x)
  9. nextPowerOfTwo(int x)