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.
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.
Simple math:
log2 (x) = logy (x) / logy (2)
where y can be anything, which for standard log functions is either 10 or e.
Consult your basic mathematics course, log n / log 2
. It doesn't matter whether you choose log
or log10
in this case, dividing by the log
of the new base does the trick.
As stated on http://en.wikipedia.org/wiki/Logarithm:
logb(x) = logk(x) / logk(b)
Which means that:
log2(x) = log10(x) / log10(2)
What you're looking to do is logarithmic change of base, which is well documented and easy to do.
If you want to compute log2 for integers, try this: http://en.wikipedia.org/wiki/Binary_logarithm#Algorithm
If you're looking for an integral result, you can just determine the highest bit set in the value and return its position.
C99 (the latest version of C), has log2
(as well as log2f
and log2l
for float and long double).