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

Audited: 2026-06-12 11:26 EDT

Implementation

int nextPowerOfTwo(int n) {
  if (n <= 0) return 1;
  int v = n - 1;
  // Smear the highest set bit down into every lower bit, then add 1. Dart ints
  // are 64-bit, so the shift chain MUST reach 32: stopping at 16 (the 32-bit
  // recipe) leaves inputs above 2^32 with an unfilled high half, producing a
  // wrong result.
  v |= v >> 1;
  v |= v >> 2;
  v |= v >> 4;
  v |= v >> 8;
  v |= v >> 16;
  v |= v >> 32;
  return v + 1;
}