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

前端 未结 4 837
再見小時候
再見小時候 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:01

    Basically, it's going to cycle through the values, when you reach the max and add 1 it's going to be the lowest value, so 32768 is going to be -32768, when you reach 65536 (32768*2) it's going to be 0 and when you reach 98303 (32768*2+32767) it's going to be 32767, if you add one you'll get to 98304 (32768*3) and it's going to be -32768 again.

    So 40002 (which is higher than 32768 but lower than 32768*2) is clearly going to be a negative number when converted to short.

    0 讨论(0)
  • 2021-01-18 16:04

    Thank all of you guys. According to all of your answers, I summarize as follows: 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
    

    When JVM regard 10011100 01000010 as a short integer, it will compute it like this:

    -2^15 + 00011100 01000010 = -32768 + 7234 = -25534
    

    This is it.

    0 讨论(0)
  • 2021-01-18 16:07

    Integer overflow happened.

    A short is two signed bytes, which means that Short.MAX_VALUE is 215-1, which is 32,767. "Larger" values logically "wrap around" into the negative range.

    In this case the excess amount is 40,002 - 215 = 7234
    Short.MIN_VALUE is -215 = -32,768
    -32,768 + 7234 = -25,534

    which is the number you're wondering about.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题