当一个长整数被投入一个短整数时,会发生什么? [英] When a long integer is cast into a short one, what happened?

查看:334
本文介绍了当一个长整数被投入一个短整数时,会发生什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用java将一个长整数y复制到一个短整数x:

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);

结果是:x现在等于-25534。

The result is: x now equals -25534.

我试图弄清楚40002是如何投入-25534的,但我失败了。 40002对应1001 1100 0100 0010,-25534对应1110 0011 1011 1110.任何朋友都可以告诉我这个过程中发生了什么?非常感谢!

I tried to figure out how 40002 was cast into -25534, but I failed. The 40002 corresponds to 1001 1100 0100 0010, the -25534 corresponds to 1110 0011 1011 1110. Can any friend tell me what happened in this process? Thanks a lot!

推荐答案

通过投射 long 你做了什么到缩小基元转换,由 JLS,第5.1.3节

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:


有符号整数到整数类型T的缩小转换只会丢弃除n个最低位之外的所有位,其中n是用于表示类型T的位数。除了可能丢失有关的信息之外数值的大小,这可能导致结果值的符号与输入值的符号不同。

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.

long value 40002 是以下64位:

The long value 40002 is the following 64 bits:

00000000 00000000 00000000 00000000 00000000 00000000 10011100 01000010

转换仅保留最低有效16位s:

The conversion only retains the least significant 16 bits:

10011100 01000010

前导 1 以2的补码表示法解释为-2 ^ 15,而不是+ 2 ^ 15。这就解释了为什么 long 值和 short 值之间的差异为2 ^ 16,65,536。

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.

这篇关于当一个长整数被投入一个短整数时,会发生什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆