Given an integer, how do I find the next largest power of two using bit-twiddling?

Viewed 40735

If I have a integer number n, how can I find the next number k > n such that k = 2^i, with some i element of N by bitwise shifting or logic.

Example: If I have n = 123, how can I find k = 128, which is a power of two, and not 124 which is only divisible by two. This should be simple, but it eludes me.

17 Answers

If you use GCC, MinGW or Clang:

template <typename T>
T nextPow2(T in)
{
  return (in & (T)(in - 1)) ? (1U << (sizeof(T) * 8 - __builtin_clz(in))) : in;
}

If you use Microsoft Visual C++, use function _BitScanForward() to replace __builtin_clz().

Related