tags:

views:

213

answers:

4
+2  Q: 

Binary math

If I know the number number y and know that 2^x=y, how do I compute x?

+11  A: 

Base 2 logarithm function:

log2(y)

which is equivalent to:

log(y) / log(2)

for arbitrary base.

Mehrdad Afshari
That log trick is so handy... I was always wondering how to do arbitrary base logs on calculators.
Zifre
Thanks! I was actually on to that answer but my check on the calculator told me otherwise. I then realised the calculator uses log10.
Johan Öbrink
BTW, I have a question : don't you have to ensure that parameters you provide to log2 are strictly positive ?
yves Baumes
@yves: It's a math question and it's not concerned about implementation details. log is not defined for negative numbers (not considering complex numbers, of course), so yes, you might want to validate the input in real world applications.
Mehrdad Afshari
If we add negative numbers into the picture: http://www.technick.net/public/code/cp_dpage.php?aiocp_dp=guide_dft_logarithms_negative_imagina
Mehrdad Afshari
+2  A: 

If you are sure that it is a power of 2, then you can write a loop and right shift the number until you get a 1. The number of times the loop ran will be the value of x.

Example code:

int power(int num)
{
    if(0 == num)
    {
     return 0;
    }

    int count = 0;
    do
    {
     ++count;
     num = num >> 1;
    }while(! (num & 1) && num > 0);
    return count;
}
Naveen
Yeah, provided that x is guaranteed to be an integer of course. This *would* be the most efficient method in that case.
Noldorin
Most processors have built in way for doing this in a single instruction (`bsr` in x86, for instance)
Mehrdad Afshari
+2  A: 

And in case you don't have a log function handy, you can always see how many times you must divide y by 2 before it becomes 1. (This assumes x is positive and an integer.)

Artelius
Brute force approach, always good :) Probably quicker for small values of y than trying to take a log as well (optimisation anyone? 'if y < 1000000 do_division() else take_log()' :))
workmad3
Funny, that. If you have a coprocessor, the threshold where the log is faster will be fairly low.
Artelius
A: 

If x is a positive integer, then, following code will be more efficient..

   unsigned int y; // You know the number y for which you require x..
   unsigned int x = 0; 

   while (y >>= 1) 
   {
         x++;
   }

x is the answer!

lakshmanaraj