nextPowerOfTwo method

int nextPowerOfTwo (int n)

Returns a number which:

  1. is a power of 2, and 2) is >= n

Implementation

static int nextPowerOfTwo(int n) {
  n--;
  n |= n >> 1; // Divide by 2^k for consecutive doublings of k up to 32,
  n |= n >> 2; // and then or the results.
  n |= n >> 4;
  n |= n >> 8;
  n |= n >> 16;
  n++; // The result is a number of 1 bits equal to the number
  // of bits in the original number, plus 1. That's the
  // next highest power of 2.
  return n;
}