java Java中的short和char类型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5058859/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 09:13:17  来源:igfitidea点击:

short and char type in Java

java

提问by shreyasva

According to the Java standard the shortand chartypes both use 2 bytes so when I code something like:

根据 Java 标准,shortchar类型都使用 2 个字节,所以当我编码时:

char ch = 'c';
short s = ch;

There is an error saying "possible loss of precision". What am I missing here?

有一个错误说“可能会损失精度”。我在这里错过了什么?

回答by Peter Knego

charis unsigned, shortis signed.

char未签名,short已签名。

So while they are both 2-byte long, they use the sixteenth bit for different purposes.

因此,虽然它们都是 2 字节长,但它们将第 16 位用于不同的目的。

The range of the chartype is 0 to 2^16 - 1 (0 to 65535).

char类型的范围是 0 到 2^16 - 1(0 到 65535)。

The shortrange is -2^15 to 2^15 - 1 (?32,768 to 32,767).

short范围是-2 ^ 15〜2 ^ 15 - 1(?32,768至32,767)。

回答by Michael Borgwardt

The difference is that charis unsigned, shortis signed. Thus, half the range of values of charis too big to be represented as a short(and of course, in symmetry, charcannot represent any of the negative values shortcan).

不同的是,char是无符号的,short是有符号的。因此, 的值范围的一半char太大而无法表示为 a short(当然,在对称性中,char不能表示任何负值short都可以)。