The ilogb functions (C99) - ilogb, ilogbf, ilogbl

符号付き int の値として引数の指数を抽出します.

ilogb (C99)

#include <math.h>
int ilogb(
    double x
);

ilogb 関数は double 型の引数 x の指数を抽出し,int 型で返します.

ilogbf (C99)

#include <math.h>
int ilogbf(
    float x
);

ilogbf 関数は float 型の引数 x の指数を抽出し,int 型で返します.

ilogbl (C99)

#include <math.h>
int ilogbl(
    long double x
);

ilogbl 関数は long double 型の引数 x の指数を抽出し,int 型で返します.

ilogb,ilogbf,ilogbl 関数は,x が 0 の場合に値域エラー (range error) が発生することがあります.

戻り値

  • x が 0 の場合: FP_ILOGB0
  • x が無限大の場合: INT_MAX
  • x が NaN (非数) の場合: FP_ILOGBNAN
  • x が上記以外の場合: 指数

C言語サンプルプログラム

以下にilogb 関数を使用したサンプルプログラムを示します.

/* header files */
#include <stdio.h>
#include <stdlib.h>
#include <math.h>

/* main */
int main(void) {
    double x;
    int y;

    x = pow(2.0, 3.0);
    y = ilogb(x);
    printf("ilogb(%.3f) =  %d\n", x, y);

    x = pow(2.0, 2.0);
    y = ilogb(x);
    printf("ilogb(%.3f) =  %d\n", x, y);

    x = pow(2.0, 1.0);
    y = ilogb(x);
    printf("ilogb(%.3f) =  %d\n", x, y);

    x = pow(2.0, -1.0);
    y = ilogb(x);
    printf("ilogb(%.3f) = %d\n", x, y);

    x = pow(2.0, -2.0);
    y = ilogb(x);
    printf("ilogb(%.3f) = %d\n", x, y);

    x = pow(2.0, -3.0);
    y = ilogb(x);
    printf("ilogb(%.3f) = %d\n", x, y);

    return EXIT_SUCCESS;
}

実行例

サンプルプログラムの実行結果は以下のようになります.

ilogb(8.000) =  3
ilogb(4.000) =  2
ilogb(2.000) =  1
ilogb(0.500) = -1
ilogb(0.250) = -2
ilogb(0.125) = -3

Cプログラマの必読書

たくさんあるC言語関連の書籍の中でも特に役に立った本です.よかったら参考にしてみてください.

C実践プログラミング 第3版

C言語の実践的参考書.少々値段は張りますが初心者を脱しようとしている人は絶対に読むべきです.
文法だけでなく,コーディングスタイルやデバッグなど文字通り「実践的」なことが書かれているので非常にためになります. オライリーの本は,読みにくい本が多いのですが本書はとても読みやすくオススメです.


C言語ポインタ完全制覇 (標準プログラマーズライブラリ)

ポインタの解説書としては最高の書籍です.
この1冊でポインタを完全に理解することができます.全くの初学者が読むには敷居が高いですが,入門書を読み終えた後に読むと非常に有益です.