Hi everybody,

is there a simple way to print a floating point number in its internal representation
(i.e. binary or hex) in C(C++)? Yet another question -- is there a linux utility to do the opposite thing with a binary file (i.e. choose a range of bits and convert it to a floating point number)?

Thanks.

Best regards,
Nick.

Hi everybody,

is there a simple way to print a floating point number in its internal representation
(i.e. binary or hex) in C(C++)? Yet another question -- is there a linux utility to do the opposite thing with a binary file (i.e. choose a range of bits and convert it to a floating point number)?

Thanks.

Best regards,
Nick.

Here's a program that writes a float or double in the form 2^exp * mantissa, with the mantissa expanded in binary. IEEE specs might call for an offset of the exponent.

#include <iostream.h>

main()
{  double x, mant;  
    int exp = 0;
     cout << "Enter postive x: ";
      //Now find exponent and mantissa
      mant = x;
      while (mant >= 1)
      { mant /= 2;
         exp++;
           // At this point x = mant * 2^(exp)
     }
      while (mant < 0.5) 
      {     mant *= 2;
              exp--;
      }
      cout << x<<" is stored in the computer as \n"<< x <<" = ";
     cout <<"2^(" <<exp<<") *.";
     while (mant > 0)
     {   mant *= 2;
          if (mant >= 1)
         {  cout << '1';
            mant -= 1;
        }
            else
            cout << '0';
    }
          cout << endl;
}

I hope I haven't incorrectly entered this code. I have to find out how to upload a code from my hard disk.

I know this is an old thread, but there is a simpler way of doing this I think:

#include <iostream>
#include <bitset>

void float_bin(float f)
{
    int x = *(int *)&f;
    std::bitset<sizeof(int) * 8> binary(x);
    std::cout << binary << std::endl;    
}
This article has been dead for over six months. Start a new discussion instead.