Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why casting division by zero to integer primitives gives different results?

    System.out.println((byte) (1.0/0));
    System.out.println((short) (1.0/0));
    System.out.println((int) (1.0/0));
    System.out.println((long) (1.0/0));

The result is:

    -1
    -1
    2147483647
    9223372036854775807

In binary format:

    1111 1111
    1111 1111 1111 1111
    0111 1111 1111 1111 1111 1111 1111 1111
    0111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111 1111

Why casting infinity to int and long integers keeps sign bit as "0", while sets sign bit to "1" for byte and short integers?

like image 505
Alexander Radchenko Avatar asked Mar 25 '16 20:03

Alexander Radchenko


1 Answers

JLS 5.1.3:

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.

In the second step:

If T is int or long, the result of the conversion is the result of the first step.

If T is byte, char, or short, the result of the conversion is the result of a narrowing conversion to type T (§5.1.3) of the result of the first step.

So an infinite double value is first cast to int by returning Integer.MAX_VALUE, and then it is further cast to byte/short, which takes the appropriate number of low bytes (and gets -1 as a result). Casts to int and long don't have that extra step, but byte and short go first through int and then to byte/short.

like image 175
Louis Wasserman Avatar answered Nov 07 '22 08:11

Louis Wasserman