(int)(char)(byte)-1;//结果是65535
(int)(short)(byte)-1;//结果是-1
(int)( ((char)(byte)-1) | 0xffff0000);//-1
byte[8bits],short[16bits],int[32bits],long是signed[64bits],而char[16bits]是unsigned。
窄类型转换为宽类型的规则是:
1 如果窄类型是signed,则符号位扩展到高位
2 如果窄类型是unsigned,则0扩展到高位。
综合成一句:
窄类型转换为宽类型,符号位会扩展到高位。
宽类型转换为窄类型,直接除去高位。
为了避免一些出乎意料的符号位扩展,可以在代码中明确是否扩展。
byte[] b = new byte[]{(byte) 0xdf}; int a2 = b[0]; System.out.println(Integer.toHexString(a2));//ffffffdf System.out.println(Integer.toHexString(a2 & 0xff));//df
If you are converting from a char value c to a wider type and you don't want sign extension, consider using a bit mask for clarity, even though it isn't required:
int i = c & 0xffff;
Alternatively, write a comment describing the behavior of the conversion:
int i = c; // Sign extension is not performed
If you are converting from a char value c to a wider integral type and you want sign extension, cast the char to a short, which is the same width as a char but signed. Given the subtlety of this code, you should also write a comment:
int i = (short) c; // Cast causes sign extension
由byte扩展成char,会导致符号位扩展,char不会得出我们想要的效果,因此我们需要人工去掉扩展。原理是利用b和整数0xff做与操作,返回宽类型int,去掉了高位的符号位,最后再缩窄为char类型。
If you are converting from a byte value b to a char and you don't want sign extension, you must use a bit mask to suppress it. This is a common idiom, so no comment is necessary:
char c = (char) (b & 0xff);
If you are converting from a byte to a char and you want sign extension, write a comment:
char c = (char) b; // Sign extension is performed
The lesson is simple: If you can't tell what a program does by looking at it, it probably doesn't do what you want. Strive for clarity.