KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
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.
Tags (comma-separated)
Save Edits
Cancel