缩小转换是指将可以保存较大值的数据类型放入可以保持最大值较小的数据类型.
long l = 4L;
int i = (int)l;
Run Code Online (Sandbox Code Playgroud)
但是我不明白为什么一个char的缩写是一个缩小的转换,但我有直觉它与这两种数据类型的有符号/无符号有关但我无法解释原因.
short s = 4; // short max value is 32767
char c = (char)s; // char max value is 65535
Run Code Online (Sandbox Code Playgroud)
它看起来像是一个扩大的转换,或者至少既不缩小也不扩宽,因为它们都是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
Run Code Online (Sandbox Code Playgroud)
这是因为a 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.
Run Code Online (Sandbox Code Playgroud)
-n当施放时char,(负)数变为2^16-n.所以,-124成为
2^16-124 = 65412
我希望这有帮助.
| 归档时间: |
|
| 查看次数: |
1078 次 |
| 最近记录: |