Search code examples
cieee-754

how to convert int type to ieee754?


I am trying to print out IEEE754 after taking integer type but it does not show the proper answer for me. I want to pass the integer to the function "void ieee(int x)" in the main method, then it will print out the IEEE754 format.

#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;       
 }

Solution

  • You are doing a type punning between an int and a struct type holding the internal representation of a float.

    This will give you wrong answers.

    If you want to know the floating-point representation of an integer number, the correct result can be obtained by doing a previous cast to float.

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

    Besides, take in account that one cannot assume that IEEE floating-point representation is being used for float.
    For example, see this link:

    Macro __STDC_IEC_559__

    On the other hand, bit-fields are not necessarily contiguous in all implementations.

    See Bitfield disadvantages.