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.
Related questions for some specific languages:
- C: Rounding up to next power of 2
- C++: Algorithm for finding the smallest power of two that's greater or equal to a given value (including C++20
std::bit_ceil())
For 32-bit integers, this is a simple and straightforward route:
Here’s a more concrete example. Let’s take the number 221, which is 11011101 in binary:
There’s one bit in the ninth position, which represents 2^8, or 256, which is indeed the next largest power of 2. Each of the shifts overlaps all of the existing 1 bits in the number with some of the previously untouched zeroes, eventually producing a number of 1 bits equal to the number of bits in the original number. Adding one to that value produces a new power of 2.
Another example; we’ll use 131, which is 10000011 in binary:
And indeed, 256 is the next highest power of 2 from 131.
If the number of bits used to represent the integer is itself a power of 2, you can continue to extend this technique efficiently and indefinitely (for example, add a
n >> 32line for 64-bit integers).