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

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

提交回复
热议问题