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
short and char type in Java
提问by shreyasva
According to the Java standard the short
and char
types both use 2 bytes so when I code something like:
根据 Java 标准,short
和char
类型都使用 2 个字节,所以当我编码时:
char ch = 'c';
short s = ch;
There is an error saying "possible loss of precision". What am I missing here?
有一个错误说“可能会损失精度”。我在这里错过了什么?
回答by Peter Knego
char
is unsigned, short
is 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 char
type is 0 to 2^16 - 1 (0 to 65535).
char
类型的范围是 0 到 2^16 - 1(0 到 65535)。
The short
range 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 char
is unsigned, short
is signed. Thus, half the range of values of char
is too big to be represented as a short
(and of course, in symmetry, char
cannot represent any of the negative values short
can).
不同的是,char
是无符号的,short
是有符号的。因此, 的值范围的一半char
太大而无法表示为 a short
(当然,在对称性中,char
不能表示任何负值short
都可以)。