Java Power of 2 nextPowerOfTwo(int x)

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

Description

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.

License

Open Source License

Declaration

public final static int nextPowerOfTwo(int x) 

Method Source Code

//package com.java2s;

public class Main {
    /**//from ww w. j av  a  2 s.  com
     * 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. This
     * process yields a bit vector with the same most significant 1 as x, but all 1's below it. Adding
     * 1 to that value yields the next largest power of 2.
     */
    public final static int nextPowerOfTwo(int x) {
        x |= x >> 1;
        x |= x >> 2;
        x |= x >> 4;
        x |= x >> 8;
        x |= x >> 16;
        return x + 1;
    }
}

Related

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