ilogb() Function
The ilogb()
function in C computes the integral part of the binary logarithm of the absolute value of a given floating-point number, revealing the exponent used internally to represent the value in a normalized format. It is useful for understanding the scale of floating-point numbers in terms of the machine’s radix.
Syntax of ilogb()
int ilogb(double x);
int ilogbf(float x);
int ilogbl(long double x);
Parameters
Parameter | Description |
---|---|
x | The value for which the binary logarithm is computed. |
Return Value
For a normal floating-point number, ilogb()
returns the exponent corresponding to the normalized representation (using FLT_RADIX, which is typically 2). For subnormal numbers, it returns the exponent as if the number were normalized to the standard form. Special cases include:
- Zero: returns
FP_ILOGB0
. - NaN: returns
FP_ILOGBNAN
. - Infinite values: return
INT_MAX
.
Note that the result from ilogb()
is generally one less than the exponent provided by frexp()
due to differences in significand normalization. In cases where the magnitude of the result is too large, an overflow range error may occur.
Examples for ilogb()
Example 1: Calculating the Exponent for a Normal Floating-Point Number
This example demonstrates how ilogb()
computes the binary logarithm of a typical floating-point number.
Program
#include <stdio.h>
#include <math.h>
int main() {
double num = 20.0;
int exponent = ilogb(num);
printf("The exponent for %f is: %d\n", num, exponent);
return 0;
}
Explanation:
- A floating-point number with the value 20.0 is defined.
- The
ilogb()
function computes the integral binary logarithm (exponent) of the number. - The calculated exponent is printed to the console.
Program Output:
The exponent for 20.000000 is: 4
Example 2: Handling Special Cases: Zero, Infinity, and NaN
This example illustrates the behavior of ilogb()
when processing special values like zero, infinity, and NaN.
Program
#include <stdio.h>
#include <math.h>
#include <limits.h>
int main() {
double zero = 0.0;
double inf = 1.0 / 0.0;
double nan = 0.0 / 0.0;
int exp_zero = ilogb(zero);
int exp_inf = ilogb(inf);
int exp_nan = ilogb(nan);
printf("ilogb(0.0) = %d\n", exp_zero);
printf("ilogb(inf) = %d\n", exp_inf);
printf("ilogb(NaN) = %d\n", exp_nan);
return 0;
}
Explanation:
- The program tests three special cases: zero, infinity, and NaN.
Program Output:
ilogb(0.0) = -2147483648
ilogb(inf) = 2147483647
ilogb(NaN) = -2147483648