How to calculate log2 of any number?

10 09 2008


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.

Advertisements