怎么把int类型转换成ieee754?

时间:2019-05-06 03:04:20

标签: c ieee-754

我正在尝试采用整数类型后打印出IEEE754,但是它没有为我显示正确的答案。 我想在main方法中将整数传递给函数“ void ieee(int x)”,然后它将打印出IEEE754格式。

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

int binary(int n, int i) 
{
    int k;
    for (i--; i >= 0; i--)
   {
      k = n >> i;
      if (k & 1)
      printf("1");
      else
      printf("0");
    }
}

typedef union
{
  int f;
  struct
  {
        unsigned int mantissa : 23;
        unsigned int exponent : 8;
        unsigned int sign : 1;
   } field;
} myfloat;

void ieee(int x)
{

int i;

myfloat var = (myfloat)x;



printf("%d ",var.field.sign);

binary(var.field.exponent, 8);
printf(" ");

binary(var.field.mantissa, 23);
printf("\n");
}

int main()
{
int x = 3;
ieee(x);

return 0;       
 }

2 个答案:

答案 0 :(得分:1)

您正在执行intstruct类型之间的类型修饰,其中包含float的内部表示形式。

这将给您错误的答案。

如果您想知道整数的浮点表示形式,则可以通过对float进行先前的强制转换来获得正确的结果。

int x = 3;
myfloat var;
var.f = (float)x; 
binary(var.field.exponent, 8);
binary(var.field.mantissa, 23);

此外,请考虑到不能假设float使用了IEEE浮点表示。
例如,请参见以下链接:

Macro __STDC_IEC_559__

另一方面,位域不一定在所有实现中都是连续的。

请参见Bitfield disadvantages

答案 1 :(得分:0)

以下内容使用并集将float的表示形式重新解释为32位无符号整数。这在C语言中是有效的。在C ++中,不能为此使用并集,因此有必要像float那样将字节从memcpy复制到整数。

#include <limits.h> //  For CHAR_BIT (overkill but demonstrates some portability).
#include <stdint.h>
#include <stdio.h>


static void DisplayFloat(float x)
{
    //  Use a union to reinterpret a float as a 32-bit unsigned integer.
    union { float f; uint32_t u; } t = { x };

    //  Ensure float and uint32_t are the same width.
    _Static_assert(sizeof t.f == sizeof t.u,
        "float and uint32_t must be same width.");

    //  Display the bits of the unsigned integer.
    for (int i = sizeof t.u * CHAR_BIT - 1; 0 <= i; --i)
        putchar('0' + (t.u >> i & 1));
    putchar('\n');
}


int main(void)
{
    DisplayFloat(3);
}