Gold mine of Visual C++ tricks!
How to calculate log2 of any number?
![]()
Few days back, my client give me one 4 inch long and 2 inch wide math equation to implement. Well, the equation contains log2 and while coding, my Visual Assist was not auto filling the log2 function. It just underlines the function by redline. When i checked the MSDN, I was shocked that log2 is not available as the part of standard library. So how to get the log2 of a number?

![]()
Log2 is pretty simple, nah? Its implementation as follows,
#include <math.h>
...
// Calculates log2 of number.
double Log2( double n )
{
// log(n)/log(2) is log2.
return log( n ) / log( 2 );
}
![]()
Its silly function, But I still blame standard library for not including it. Because I’m lazy.
![]()
Targeted Audience – Beginners.
| Print article | This entry was posted by Jijo Raj on September 10, 2008 at 6:59 pm, and is filed under C++, Codeproject. Follow any responses to this post through RSS 2.0. You can leave a response or trackback from your own site. |
about 1 year ago
the calculation line in the function should read
return log( n ) / log( 2.0 );
because log(2) is ambiguous; the C++ compiler doesn’t realise it’s a double!