Search code examples
language-agnosticfloating-point

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


I'd like to display the binary (or hexadecimal) representation of a floating point number. I know how to convert by hand (using the method here), but I'm interested in seeing code samples that do the same.

Although I'm particularly interested in the C++ and Java solutions, I wonder if any languages make it particularly easy so I'm making this language agnostic. I'd love to see some solutions in other languages.

EDIT: I've gotten good coverage of C, C++, C#, and Java. Are there any alternative-language gurus out there who want to add to the list?


Solution

  • C/C++ is easy.

    union ufloat {
      float f;
      unsigned u;
    };
    
    ufloat u1;
    u1.f = 0.3f;
    

    Then you just output u1.u.

    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().