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"
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". Show activity on this post.
The conversion between a floating point number (i.e. a 32 bit area in memory) and the bit representation isn't actually a conversion, but just a reinterpretation of the same data in memory. This can be easily done with typecasts in C/C++ or with some bitfiddling via java.lang.Float.floatToIntBits in Java.
To convert a floating point decimal number into binary, first convert the integer part into binary form and then fractional part into binary form and finally combine both results to get the final answer. For Integer Part, keep dividing the number by 2 and noting down the remainder until and unless the dividend is less than 2.
Byte Array to Float Conversion Let's now convert a byte array into a float using Float class function intBitsToFloat. However, we need to first convert a byte array into int bits using the left shift: Converting a byte array into a float using ByteBuffer is as simple as this: 4. Unit Testing 5. Conclusion
long bits = Double.doubleToLongBits(myDouble);
System.out.println(Long.toBinaryString(bits));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With