tags:

views:

193

answers:

9

Is there any way to write log(base 2) function?

the c language has 2 built in function -->>

1.log which is base e.

2.log10 base 10;

But i need log function of base 2.How to calculate this.Someone help me.

+19  A: 

Simple math:

    log2 (x) = logy (x) / logy (2)

where y can be anything, which for standard log functions is either 10 or e.

Adam Crume
Thanx a lot.I got my answer.
russell
@russell, you should accept this answer then.
Mark Ransom
A: 

Consult your basic mathematics course, log n / log 2. It doesn't matter whether you choose log or log10in this case, dividing by the log of the new base does the trick.

Pieter
A: 
log2(x) = log10(x) / log10(2)
the_void
+2  A: 

As stated on http://en.wikipedia.org/wiki/Logarithm:

logb(x) = logk(x) / logk(b)

Which means that:

log2(x) = log10(x) / log10(2)
Patrick
Note that you can precompute log10(2) to increase performance.
glowcoder
@Johannes that's a good point.
glowcoder
@Johannes: I doubt the compiler will pre-compute log10(2). The compiler doesn't know that log10 will return the same value every time. For all the compiler knows, log10(2) could return different values on successive calls.
abelenky
@abelenky: Ok, I take that back. Since the compiler never sees the source to the `log()` implementation it won't do it. My bad.
Joey
@abelenky: Since `log10()` is a function defined in the C standard, the compiler is free to treat it "specially", including precomputing the result, which I believe was @Johannes' suggestion?
caf
A: 

What you're looking to do is logarithmic change of base, which is well documented and easy to do.

fbrereto
A: 

If you want to compute log2 for integers, try this: http://en.wikipedia.org/wiki/Binary_logarithm#Algorithm

lhf
+3  A: 

If you're looking for an integral result, you can just determine the highest bit set in the value and return its position.

tomlogic
+1 for elegance
Justin L.
There is also a nice bit-twiddling method for this (taken from Java's `Integer.highestOneBit(int)` method): `i |= (i >> 1); i |= (i >> 2); i |= (i >> 4); i |= (i >> 8); i |= (i >> 16); return i - (i >>> 1);`
Joey
+1  A: 

C99 (the latest version of C), has log2 (as well as log2f and log2l for float and long double).

Matthew Flaschen