Why is a long type smaller than the range of float types? 2015-09-15 22:36 680 People read Comments (0) favorite reports
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
As a common sense, we all know that the floating-point type occupies 4 bytes of space in memory, while the long type occupies 8 bytes of space. But why did you make a mistake in writing a Java program today, and finally know that the maximum value for a 4-byte float would be greater than the maximum of long. I was surprised to find this mistake, so I looked up the data before I knew the reason.
As we all know, the range of float type is: one 3.403e38~3.403e38. The range of the long type is: -2^63~2^63-1 (presumably 9*10^18).
I used to remember that even if it was done, I didn't think about it.
Let me share with you what I understand now:
The long integer, which occupies 8 bytes in memory, has a total of 64 bits, it represents a value of 2 of 64 square, is equally positive and negative, the value range is minus 2 63 times to 2 square 63.
and float occupies 4 bytes in memory, a total of 32 bits, but the floating-point numbers are in memory:
v= ( -1) ^s * M * 2^e
The 32 bits of a floating-point number are not simply direct representations of size, but are assigned according to certain criteria.
Where the 1th bit, the sign bit, i.e. S.
The next 8 bits, the exponential field, E.
The remaining 23 bits, the decimal field, that is, the value range of m,m or [0,1].
That is, the floating-point number in the memory of the binary value is not directly converted to decimal values, but in accordance with the above formula calculation, through this formula, although only 4 bytes, but the floating-point number is larger than the maximum value of long integer.
This is why the long type is the root cause of the float type when converting data.
Why is a long type in Java smaller than the range of float types?