What is the simplest function to return the smallest power of 2 that is greater than or equal to a given non-negative integer in Python?
For example, the smallest po
Always returning 2**(x - 1).bit_length() is incorrect because although it returns 1 for x=1, it returns a non-monotonic 2 for x=0. A simple fix that is monotonically safe for x=0 is:
def next_power_of_2(x):
return 1 if x == 0 else 2**(x - 1).bit_length()
Sample outputs:
>>> print(', '.join(f'{x}:{next_power_of_2(x)}' for x in range(10)))
0:1, 1:1, 2:2, 3:4, 4:4, 5:8, 6:8, 7:8, 8:8, 9:16
It can pedantically be argued that x=0 should return 0 (and not 1), since 2**float('-inf') == 0.