# Finding the nearest power of 2 with a formula

Is there any simple formula that can be used to find the nearest power of 2 of a number?

So, let's say I got the number $$15$$, it has to give $$16$$, If I got the number $$55$$, it gives me $$64$$, etc.

• Nearest in what sense? is $12$ "nearer" to $8$ or is it "nearer" to $16$? What about $11.5$? Whatever your final interpretation, play with $\log_2$ and floor/ceiling functions. Dec 5, 2019 at 14:56
• indeed, if it is the same distance to two power of 2's, it can use any of the two. I was wondering if their is a closed form formula, without using floor/ceiling functions... Dec 5, 2019 at 14:57
• Given the very nature of what you are describing as being a step function of sorts... a floor or ceiling is almost guaranteed in some form. Dec 5, 2019 at 14:58
• If you convert you number into binary, you can easily do this Dec 5, 2019 at 14:59
• @Steven31415 Not true. That would make $2^{n+1/2}$ the dividing line between $2^n$ and $2^{n+1}$, but it should be $3 \cdot 2^{n-1}$. Dec 5, 2019 at 15:09

$$a=\log_2 x- \lfloor \log_2 x \rfloor$$
$$b=\lceil \log_2 x \rceil -\log_2 x$$
If $$min\{a,b\}=a$$ then the nearest power of $$2$$ is $$2^{\lfloor \log_2 x \rfloor}$$,
Else it is $$2^{\lceil \log_2 x \rceil }$$