Which algorithm does java uses to convert floating point number (Ex:0.15625) into binary(0.00101)?
Whether java uses normalized form or denormalized format?
If I type float ab=0.15625
in Java source file, which part of compiling and running the code will convert that floating point number into a format that could be stored in memory and used by the JVM?
Best Answer
The first thing to realize is that the binary representation of
0.15625
is not0.00101
. Yes, that is what you would write if you were writing out the number by hand. The actual representation of the number within the computer using IEE 754 for single precision 32 bit. This is specified as part of the Java Language Specification 4.2:The IEEE 754 binary representation of
0.15625
is:0x3E200000
which can be broken down into:0
meaning it is positive.01111100
which is 124. This value is subtracted from 127 to get the actual exponent that will be used (-3
).0100000 00000000 00000000
. The.
I put there is for reading so that it is bytes, not part of the value (the significant uses the lower 23 bits of the number... so the 24th bit I represent with a.
so the alignment is easier to read) This value is added to1
giving us the binary value of1.010....
or in base 10,1.25000...
Combining these all together, we get:
(-1)
0
*1.01
2 * 2-3 which comes out to be, when written,0.00101
. But remember, that we're really dealing with0x3E200000
.Lets take a quick Java source file:
The byte code for this, when decompiled is:
Which really isn't too interesting. You can see the
LDC 0.15625
in there which is a load constant opcode. It takes one argument from a constant pool and pushes it on the stack.So, lets look at Demo.class with a hex dump viewer.
Look, right there at the start of the second line...
There's the number.
Someone is going to ask 'but why is the number way up there? There's not even a
12
near it (the hex value forLDC
).' And they are right to ask this. Remember that the LDC tool a value from the constant pool. The byte code that I had earlier was converted back into something a person could read.The structure of a class file can be found in the Java Virtual Machine Specification section 4.1:
We've got the magic number at the top (
ca fe ba be
), and the minor version (00 00
), and major version (00 32
= 5010) and then the constant pool count (00 15
) which then has the constant pool itself.The constant pool is specified in section 4.4 which has the format:
The tag value of
04
says that 'what is next is a float`. You can see it at the end of the preceding line.The other stuff that is around the number is information about locations for methods (it still has a default constructor), the name of the field, the name of the class, etc... there are a bunch of constants in there.
The key thing there though, you can see the floating point number stored in the class file as an IEEE 754 value that indicates this is something that the compiler does.