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.

Recommended Answers

All 5 Replies

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.

cin statement is nwys missing......... :P

commented: Useless 4-year bump award -6

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;    
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.