I need to find the smallest power of two that's greater or equal to a given value. So far, I have this:
int value = 3221; // 3221 is just an example, could be any number
int result = 1;
while (result < value) result <<= 1;
It works fine, but feels kind of naive. Is there a better algorithm for that problem?
Related: Rounding up to next power of 2 has some C answers; C++20 std::bit_ceil()
isn't available in C, so the ideas could be useful for older C++ code, too.
Most of the answers to this question predate C++20, but could still be useful if implementing a C++ standard library or compiler.
Also related: language-agnostic Given an integer, how do I find the next largest power of two using bit-twiddling? has a C++17 constexpr
answer using GNU extensions.
1 << r
to get the power of 2. – Armoirepython
: https://mcmap.net/q/19995/-given-an-integer-how-do-i-find-the-next-largest-power-of-two-using-bit-twiddling – Spleneticbit
header. The same answer cannot be given to a c question. – Drusiestd::bitceil
– Drusiestd::bit_ceil
. – Buckle