If I have a number greater than 20 but that can be divided evenly by 2 without any remainder, I want to determine what number gets me closest to 20. For example:
For 2048, dividing by 2 enough times would get me to 16 which is the closest I can get to 20. If the number is 800, the closest is 25.
I can write a loop and just keep dividing and comparing the range and pick the value that is closest. Is there maybe a simpler way, possibly through shifting bits?
EDIT: When I say it evenly divides by 2, I mean it divides all the way down to 2 as well. A number of 70 would only divide down to 35 evenly. A number like 2048 or 1024 will divide evenly all the way to 2.
Sample numbers: 2048, 1920, 1600, 1536, 1080..640, 352, 320, 176. These are typical image sizes from cameras.
If your input number is
x, I think you wantx/2^[(log x/14)/log 2], assuming you want your target number to be in the interval[14,27].In java code,
Math‘slogfunction will come in handy (although base-2 logarithm would be even better), and you also need an integer cast (or somehow find the largest integer smaller than the expression in[]).What this does: Let
xbe your input andybe the number you want to find. Then,x=y*2^nfor yet unknownn, whileyis around 20 (see above). Obviously,nis the base-2 logarithm ofx/y. Now, if you pick the smallest possibley, call ity', the integer part of the base-2 logarithm ofx/y'is still thenwe are looking for, unlessx/y'differs fromx/yby a factor of more than 2, which by assumption of repeated division by 2 it cannot. Thus, we havenand hencey=x/2^n.