I ran into an unexpected result in round-tripping Int32.MaxValue
into a System.Single
:
Int32 i = Int32.MaxValue;
Single s = i;
Int32 c = (Int32)s;
Debug.WriteLine(i); // 2147483647
Debug.WriteLine(c); // -2147483648
I realized that it must be overflowing, since Single
doesn't have enough bits in the significand to hold the Int32
value, and it rounds up. When I changed the conv.r4
to conv.r4.ovf
in the IL, an OverflowExcpetion
is thrown. Fair enough...
However, while I was investigating this issue, I compiled this code in java and ran it and got the following:
int i = Integer.MAX_VALUE;
float s = (float)i;
int c = (int)s;
System.out.println(i); // 2147483647
System.out.println(c); // 2147483647
I don't know much about the JVM, but I wonder how it does this. It seems much less surprising, but how does it retain the extra digit after roundin开发者_JAVA技巧g to 2.14748365E9? Does it keep some kind of internal representation around and then replace it when casting back to int
? Or does it just round down to Integer.MAX_VALUE
to avoid overflow?
This case is explicitly handled by §5.1.3 of the Java Language Specification:
A narrowing conversion of a floating-point number to an integral type T takes two steps:
- In the first step, the floating-point number is converted either to a long, if T is long, or to an int, if T is byte, short, char, or int, as follows:
- If the floating-point number is NaN (§4.2.3), the result of the first step of the conversion is an int or long 0.
- Otherwise, if the floating-point number is not an infinity, the floating-point value is rounded to an integer value V, rounding toward zero using IEEE 754 round-toward-zero mode (§4.2.3). Then there are two cases:
- If T is long, and this integer value can be represented as a long, then the result of the first step is the long value V.
- Otherwise, if this integer value can be represented as an int, then the result of the first step is the int value V.
- Otherwise, one of the following two cases must be true:
- The value must be too small (a negative value of large magnitude or negative infinity), and the result of the first step is the smallest representable value of type int or long.
- The value must be too large (a positive value of large magnitude or positive infinity), and the result of the first step is the largest representable value of type int or long.
精彩评论