When a long integer is cast into a short one, what happened?

前端 未结 4 836
再見小時候
再見小時候 2021-01-18 15:35

I use java to copy one long integer y to a short integer x:

long y = 40002;
short x = (short) y;
System.out.println(\"x now equals \" + x);

4条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-18 16:16

    What you have done by casting a long to a short is a narrowing primitive conversion, which is covered by the JLS, Section 5.1.3:

    A narrowing conversion of a signed integer to an integral type T simply discards all but the n lowest order bits, where n is the number of bits used to represent type T. In addition to a possible loss of information about the magnitude of the numeric value, this may cause the sign of the resulting value to differ from the sign of the input value.

    The long value 40002 is the following 64 bits:

    00000000 00000000 00000000 00000000 00000000 00000000 10011100 01000010
    

    The conversion only retains the least significant 16 bits:

    10011100 01000010
    

    That leading 1 is interpreted in 2's complement notation to be -2^15, not +2^15. That explains why there is a difference of 2^16, of 65,536, in the long value and the short value.

提交回复
热议问题