为什么对char来说简短的转换是一个缩小的转换?
缩小转换是将可以保存较大值的数据类型放入可以保持最大值较小的数据类型。
long l = 4L; int i = (int)l;
但是我不明白为什么一个char的缩写是一个缩小的转换,但我有直觉它与这两种数据类型的有符号/无符号有关,但我无法解释原因。
short s = 4; // short max value is 32767 char c = (char)s; // char max value is 65535
它看起来像是一个扩大的转换,或者至少既不缩小也不扩宽,因为它们都是16位并且可以保持相同数量的值。
System.out.println((int)Character.MIN_VALUE); //0 System.out.println((int)Character.MAX_VALUE); //65535 System.out.println(Short.MIN_VALUE); //-32768 System.out.println(Short.MAX_VALUE); //32767 //65535 = 32768+32767
这是因为short
可以保持负值而char
不像你在Character.MIN_VALUE
看到的那样。 我举几个例子。
short s = -124; char c = 124; // OK, no compile time error char d = -124; // NOT OK, compile time error since char cannot hold -ve values char e = s; // NOT OK, compile time error since a short might have -ve values which char won't be able to hold char f = (char)s; // OK, type casting. The negative number -124 gets converted to 65412 so that char can hold it System.out.println((short)f); // -124, gets converted back to a number short can hold because short won't be able to hold 65412 System.out.println((int)f); // 65412, gets converted to 65412 because int can easily hold it.
当转换为char
,(负)数字-n
变为2^16-n
。 所以, -124
变成了
2^16-124 = 65412
我希望这有帮助。
缩小的关键不在于位大小,而是在新类型中无法正确表示某些值。
正如您在最后一段代码中所示, Short.MIN_VALUE < Character.MIN_VALUE
,即某些short
值无法用char
表示。
由于你不能使用char
忠实地表示负数(演员阵容会导致负数由2的补码表示,这不是相同的数字),我们认为演员“失去信息”,从而缩小。
从Java语言规范,§5.1.3 :
原始类型的22个特定转换称为缩小基元转换:
short
到byte
或char
char
到byte
或short
- ...
缩小的原始转换可能丢失关于数值的总量值的信息,并且还可能失去精度和范围。
...
将有符号整数缩小到整数类型
T
只会丢弃除n个最低位之外的所有位,其中n是用于表示类型T
的位数。 除了可能丢失有关数值大小的信息之外,这可能导致结果值的符号与输入值的符号不同。将
char
缩小到整数类型T
同样简单地丢弃除n个最低位之外的所有位,其中n是用于表示类型T
的位数。 除了可能丢失有关数值大小的信息之外, 这可能导致结果值为负数,即使字符表示16位无符号整数值。