nextPowerOfTwo function

int nextPowerOfTwo(
  1. int n
)

Returns the smallest power of two greater than or equal to n.

Returns 1 for any n less than or equal to zero.

Example:

nextPowerOfTwo(17); // 32

Implementation

int nextPowerOfTwo(int n) {
  if (n <= 0) return 1;
  int v = n - 1;
  v |= v >> 1;
  v |= v >> 2;
  v |= v >> 4;
  v |= v >> 8;
  v |= v >> 16;
  return v + 1;
}