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

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

提交回复
热议问题