Search code examples
javafloating-pointdouble

Convert float and double to bit and hexadecimal representation in Java


How can I get single bits (or an entire variable) of a double or a float?

For example if I have float a = 0.5;

I would expect a String equal to:
"00111111000000000000000000000000"

or in hex:
"F000000"


Solution

  • For Java, a float is on 32 bits like a int, and a double is on 64 bits like a long. Finding the binary representation of these numbers, you need to:

    float a = 0.5f;
    int bits = Float.floatToIntBits(a);
    String.format("%32s", Integer.toBinaryString(bits)).replace(" ", "0");
    String.format("%8s", Integer.toHexString(bits)).replace(" ", "0");
    

    "00111111000000000000000000000000" bit representation (32 bits)
    "3f000000" hexadecimal representation (32 bits)

    double a = 0.5d;
    long bits = Double.doubleToLongBits(a);
    String.format("%64s", Long.toBinaryString(bits)).replace(" ", "0");
    String.format("%16s", Long.toHexString(bits)).replace(" ", "0");
    

    "0011111111100000000000000000000000000000000000000000000000000000" bit representation (64 bits)
    "3fe0000000000000" hexadecimal representation (64 bits)

    You can check that it works by doing the reverse operation:

    int bits = Integer.parseInt("00111111000000000000000000000000", 2);
    Float.intBitsToFloat(bits);
    

    0.5 (float)

    long bits = Long.parseLong("0011111111100000000000000000000000000000000000000000000000000000", 2);
    Double.longBitsToDouble(bits);
    

    0.5 (double)

    For the hexadecimal representation, you can use respectively Integer.parseInt("...", 16); and Long.parseLong("...", 16);