ceilingToPowerOfTwo function

int ceilingToPowerOfTwo (int number)

Find the closest perfect power of two that is larger or equal to the provided integer.

Implementation

int ceilingToPowerOfTwo(int number) {
  if (number == int64MinValue) {
    return 0;
  }

  const maxPowerOfTwo = 0x4000000000000000;
  if (number > maxPowerOfTwo) {
    throw ArgumentError('Value ${number} is out of range.');
  }

  number--;
  number |= number >> 1;
  number |= number >> 2;
  number |= number >> 4;
  number |= number >> 8;
  number |= number >> 16;
  number |= number >> 32;
  return number + 1;
}