ilogb() function in C++ STL

The ilogb(x) function in C++ STL returns the integral part of the logarithm of |x|, by using the FLT_RADIX as base for the logarithm. In general, the value of FLT_RADIX is 2, so ilogb() is equivalent to ilog2()(for positive values only).

Syntax:

ilogb(x)

Parameter: The function accepts a single mandatory parmaeter x whose ilogb() is to be calculated. The data-type can be of double, float, long double or int.

Return Value: The function returns an integral part of the logarithm of |x|, using FLT_RADIX as base for the logarithm. The function returns three exception values:

  • If the argument is NaN, it returns FP_LOGBNAN.
  • If the argument is infinite, it returns INT_MAX
  • If the argument is 0, it returns FP_LOGB0.

Below programs illustrate the above function:

Program 1:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the ilogb()
// function when input is an integer
#include <cfloat>
#include <cmath>
#include <iostream>
  
using namespace std;
  
int main()
{
    int result, x = 25;
  
    // Function to calculate ilogb(25)
    result = ilogb(x);
    cout << "ilogb (" << x << ") = " << result << endl;
  
    // Function to calculate ilogb(50)
    x = 50;
    result = ilogb(x);
    cout << "ilogb (" << x << ") = " << result << endl;
  
    return 0;
}

chevron_right


Output:

ilogb (25) = 4
ilogb (50) = 5

Program 2:
Program for non-integral type

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the ilogb()
// function when input is a double value
#include <cfloat>
#include <cmath>
#include <iostream>
  
using namespace std;
  
int main()
{
    int result, x = 11.11;
  
    result = ilogb(x);
    cout << "ilogb (" << x << ") = " << result << endl;
  
    x = 41.11;
    result = ilogb(x);
    cout << "ilogb (" << x << ") = " << result << endl;
  
    return 0;
}

chevron_right


Output:

ilogb (11) = 3
ilogb (41) = 5

Program 3:

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to illustrate the ilogb()
// function when input is 0
#include <cfloat>
#include <cmath>
#include <iostream>
#include <iostream>
  
using namespace std;
  
int main()
{
    int result, x = 0;
  
    result = ilogb(x);
    cout << "ilogb (" << x << ") = " << result << endl;
  
    return 0;
}

chevron_right


Output:

ilogb (0) = -2147483648


My Personal Notes arrow_drop_up


Article Tags :
Practice Tags :


Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.