I try to figure out how float and doubles work in Java. there is explained that we can represent 5.3 as
0 | 10000001 | 01010011001100110011001
But when I try to write it as a binary java literal
float number = 0b01000000101010011001100110011001;
System.out.println(number);
i get the output 1.0848567E9
.
If I use the way to represent 5.3 as binary from this question
int intBits = Float.floatToIntBits(5.3F);
String binary = Integer.toBinaryString(intBits);
System.out.println(binary);
i get a completely confusing result 1000000101010011001100110011010
with 1 in the first position, which as I thought means a negative sign.
May somebody help me to understand what I do wrong? Can I use binary java literals to represent floats and doubles?
Thanks.
CodePudding user response:
According to the Java Language Specification, there is no binary float literal of the form you want.
0b01000000101010011001100110011001
is an int
literal, but there is a method to convert this int
to a float
:
System.out.println(Float.intBitsToFloat(0b01000000101010011001100110011001));
This prints 5.2999997
, because your representation isn't the most accurate. A more accurate one is:
0b01000000101010011001100110011010
Using this would print 5.3.
See also the tool IEEE Floating Point Converter, which you can use to get the binary representations of floats.