Convert float to bit

How can I get single bits (or an integer variable) doubleor float?

For example, if I have float a = 0.5;

I would expect a to Stringequal:
"00111111000000000000000000000000"

or in hexadecimal format:
"F000000"

+5
source share
4 answers
long bits = Double.doubleToLongBits(myDouble);
System.out.println(Long.toBinaryString(bits));
+9
source

Take a look Float.floatToIntBits() or Float.floatToRawIntBits(). This gives you bits as an int. If you need it as a string Integer.toBinaryString().

Note that there may be a problem if HSB is turned on - you may need to convert to long to avoid overflow.

+3
source
public void printFloatBits(float f) {
    int bits = Float.floatToIntBits(f);
    // Extract each bit from 'bits' and compare it by '0'
    for (int i=31; i>=0; --i) {
        // int mask = 1 << i;
        // int oneBit = bits & mask;
        // oneBit == 0 or 1?
        System.out.print((bits & (1 << i)) == 0 ? "0" : "1");
    }
}
0

All Articles