Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

log2 — C23 mathematical function

`log2(x)` from `<math.h>` returns the base-two logarithm of positive `x`; `log2f` and `log2l` serve the other types. Powers of two produce integral results, useful for tree levels, block sizes, and bit-oriented analysis.

Version: C23

Syntax

double log2(double x);

log2(x) from <math.h> returns the base-two logarithm of positive x; log2f and log2l serve the other types. Powers of two produce integral results, useful for tree levels, block sizes, and bit-oriented analysis.

The example calls log2(1.0), log2(8.0), and log2(0.25). Output 0.0 3.0 -2.0 demonstrates the neutral point plus positive and negative powers of two.

For x < 0 there is a domain error, for zero a pole error may occur, and a very small result can underflow; use math_errhandling. Do not cast the result for arbitrary x to an integer index without proving the argument is an appropriate power. Annex F returns -∞ for ±0 and raises FE_DIVBYZERO, returns +∞ for positive infinity, and propagates NaN.

Examples

#include <math.h>
#include <stdio.h>
int main(void){printf("%.1f %.1f %.1f\n",log2(1.0),log2(8.0),log2(0.25));return 0;}

Result

0.0 3.0 -2.0

The example calls `log2(1.0)`, `log2(8.0)`, and `log2(0.25)`. Output `0.0 3.0 -2.0` demonstrates the neutral point plus positive and negative powers of two.

Sources