0
Find next and previous power of two of a given number in C
C
2 Answers
+ 9
find log2(num)
previous is 2 ^ floor(log)
next is 2 ^ ceil(log)
2 ^ x = 1 << x
+ 2
Have a variable that will store powers of 2, starting with 1. Use a while loop where you check if your number is under that variable, if not then double the value of that variable. You should be able to deduce the two powers of 2 that you were searching for.
Alternatively, do it in reverse: while your number isn't 1, divide it by 2 and count how many times you do so. More interesting if you want the exponents rather than the values of the powers of 2.
If you want more elaborated ways:
https://stackoverflow.com/questions/364985/algorithm-for-finding-the-smallest-power-of-two-thats-greater-or-equal-to-a-giv
Oh, actually math.h has a log2 function, so you can use that.