How do I display the binary representation of a float or double?

Solution 1:

C/C++ is easy.

union ufloat {
  float f;
  unsigned u;
};

ufloat u1;
u1.f = 0.3f;

Then you just output u1.u. You can adapt this implementation.

Doubles just as easy.

union udouble {
  double d;
  unsigned long u;
}

because doubles are 64 bit.

Java is a bit easier: use Float.floatToRawIntBits() combined with Integer.toBinaryString() and Double.doubleToRawLongBits combined with Long.toBinaryString().

Solution 2:

In C:

int fl = *(int*)&floatVar;

&floatVar would get the adress memory then (int*) would be a pointer to this adress memory, finally the * to get the value of the 4 bytes float in int. Then you can printf the binary format or hex format.

Solution 3:

Java: a google search finds this link on Sun's forums

specifically (I haven't tried this myself)

long binary = Double.doubleToLongBits(3.14159);
String strBinary = Long.toBinaryString(binary);