2
$\begingroup$

I need this for a GIF encoder I'm programming, if something is $2^{N+1}$, how can I get $N$ back from the end result?

For example, $2^{7+1} = 256$, how can I get back to $7$ from $256$?

I've spent over an hour with a pencil and a sheet of paper trying to remember how to "balance equations" from my time in college but i cant seem to remember...

This seems pretty basic for this site but i was pushed here from stack overflow because it "wasn't programming related.."

Hopefully I'm not posting out of place here either

$\endgroup$
  • 2
    $\begingroup$ $\log_2(x)-1$ should do the job. If you don't have $\log_2$ function in your calculator, then you can use $\frac{\log(x)}{\log(2)}-1$ instead. $\endgroup$ – barak manos Jan 16 '15 at 12:14
  • 1
    $\begingroup$ Don't worry, this site is for math questions at all levels. $\endgroup$ – bof Jan 16 '15 at 12:15
  • $\begingroup$ Yes, Regret's answer works for logs to any base. If logs to the base $2$ are available, then the formula simplifies because then $\log2=1$. $\endgroup$ – bof Jan 16 '15 at 12:17
2
$\begingroup$

$$2^{n+1}=x\\ \log(2^{n+1})=\log(x)\\ (n+1)\log(2)=\log(x)\\ n=\frac{\log(x)}{\log(2)}-1\\ $$

In mathematics, just "$\log$" usually means with base $e$, but it does not matter which base you use here. This is because $\frac{\log_a(x)}{\log_a(2)}$ is the same number for any base $a$, it is equal to $\log_2(x)$. If you have access to base $2$ logarithm, you can just use $\log_2(x)-1$. If you only have access to a logarithm with a different base, you can use $\frac{\log(x)}{\log(2)}-1$.


You should be careful if you are using floating point numbers, however. For example,

Math.log(Math.pow(2, 31))/Math.log(2)

in JavaScript results in 31.000000000000004 and not $31$ like it should if floats were accurate.

$\endgroup$
  • $\begingroup$ @James: I added a small detail to the end, do you think it is relevant? $\endgroup$ – Regret Jan 16 '15 at 12:36
  • $\begingroup$ dont think this should be an issue. After getting the number I do round up which in the case of what you said a size of 31 would come out as 32, but it only wastes a byte of data so I'm not worried about it. Thanks anyway good to know if random values show up and I cant understand why. $\endgroup$ – Trotski94 Jan 16 '15 at 12:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.