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"
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"
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);
Look at Float.floatToIntBits() or Float.floatToRawIntBits()
. That gets you the bits as an int. If you need it as a String, Integer.toBinaryString()
.
Note, there may be an issue if the HSB is on - you may need to convert to a long to avoid an "overflow".
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");
}
}
Double.byteValue()
might help you.
There is also a 32-bit equivalent Float.byteValue()
.