C言語のfloatとそのバイナリ表記を変換する関数

| ← back |
| home |

ソース
// https://www.cepstrum.co.jp/

#include <stdio.h>
#include <stdlib.h>
#include <float.h>
#include <math.h>

//================================================================

float bin2float(unsigned x) {
  float *fp=(float *)&x;

  return *fp;
}

//================================================================

unsigned float2bin(float x) {
  unsigned *up=(unsigned *)&x;

  return *up;
}

//================================================================

int main() {
  printf("%26.18e\n", bin2float(0xffc00000));    // Indeterminate
  printf("%26.18e\n", bin2float(0x7f800001));    // NaN
  printf("%26.18e\n", bin2float(0x7f800000));    // Infinity
  printf("%26.18e\n", bin2float(0xff800000));    // -Infinity
  printf("%26.18e\n", bin2float(0x00000000));    // 0
  printf("%26.18e\n", bin2float(0x80000000));    // -0
  printf("%26.18e\n", bin2float(0xa50f5af0));    // ?
  printf("%26.18e\n", bin2float(0b01011011110010010110100100100100));    // ?
  printf("\n");
  printf("0x%x\n", float2bin(0.0/0.0));
  printf("0x%x\n", float2bin(1.0/0.0));
  printf("0x%x\n", float2bin(FLT_EPSILON));
  printf("0x%x\n", float2bin(1.0-FLT_EPSILON));
  printf("0x%x\n", float2bin(1.0));
  printf("0x%x\n", float2bin(-65535.0));
}

実行結果
-1.#IND00000000000000e+000
 1.#QNAN0000000000000e+000
 1.#INF00000000000000e+000
-1.#INF00000000000000e+000
 0.000000000000000000e+000
-0.000000000000000000e+000
-1.243408367669054600e-016
 1.133841473171619800e+017

0xffc00000
0x7f800000
0x34000000
0x3f7ffffe
0x3f800000
0xc77fff00

詳細不明の作者(たぶんドイツ人の Schmidt さん)の IEEE-754 Floating Point Converter へのリンク(要JavaScript)
https://www.h-schmidt.net/FloatConverter/IEEE754.html

| ← back | ↑top |
| home |