The C log2() function is a math method used to return the base 2 logarithm value of a given number. The syntax of the log2() function is
double log2(double n);
As you can see from the above syntax, it accepts a double data type and returns the result as a double value. Any other data type is implicitly converted to a double to find the base 2 logarithm value.
C log2() function example
As it is a part of the math header file, we must include <math.h> file. The following example finds the base 2 logarithmic value of different numbers.
#include <stdio.h>
#include <math.h>
int main()
{
double a = 50.45;
double result = log2(a);
printf("%.2f\n", result);
}
5.66
Please refer to the math library log() method and log10 function articles in C Programming for natural and base 10 logarithm values.
Example 2: Here, we use the log2() function to find the base 2 logarithmic value of 0 and 1. As you can see, log2() returns -infinity for both positive and negative zero.
#include <stdio.h>
#include <math.h>
int main()
{
printf("%.2f\n", log2(0));
printf("%.2f\n", log2(-0));
printf("%.2f\n", log2(1));
}
-inf
-inf
0.00
Example 3: When we apply the C log2() function to negative numbers, it returns NaN (Not a Number) as the output. Please check the exp() and pow() functions.
#include <stdio.h>
#include <math.h>
int main()
{
printf("%.2f\n", log2(-5));
printf("%.2f\n", log2(-10));
}
-nan(ind)
-nan(ind)
C log2f() and lg2l() functions
We can use the log2f() function to work with float data types, and for long double values, use the log2l() function. Similar to the log2() function, both log2f() and log2l() functions find the base 2 logarithmic value of float and long data types and return the same data type as the output.
#include <stdio.h>
#include <math.h>
int main()
{
double a = 25.0;
double r1 = log2(a);
printf("%.2f\n", r1);
float b = 32.57f;
float r2 = log2f(b);
printf("%.2f\n", r2);
long double c = 40.75L;
long double r3 = log2l(c);
printf("%.2Lf\n", r3);
}
4.64
5.03
5.34