连续多次演员不按预期工作 [英] Multiple casts in succession not working as intended
本文介绍了连续多次演员不按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
根据我的理解,Casts用于将值从一种类型转换为另一种类型。该程序连续使用三个演员表。
As per my understanding Casts are used to convert a value from one type to another. This program uses three casts in succession.
public class Multicast {
public static void main(String[] args) {
System.out.println((int) (char) (byte) -1);
}
}
我认为它会打印-1但它正在打印它打印65535,但为什么?
I thought it will print -1 but it is printing It prints 65535, but why?
推荐答案
表达式:(int)(char)(byte) - 1
-
-1
的类型为int -
(byte)-1
是一个值为-1的字节 -
(char)(byte)-1
首先将值为-1的字节再次符号扩展为值为-1的32位整数。这意味着所有32位都设置为1(32位的-1的双补码编码)。然后它被转换为类型char
这是一个无符号的16位值,因此你将16位设置为1,其值为65535。 -
(int)(char)(byte)-1
通过将其再次显式地转换为32位整数,确保将其打印为一个数字而不是代码点65535的字符。
-1
is of type int(byte) -1
is a byte with value -1(char) (byte) -1
first the byte with value -1 is sign extended again to be an 32-bit integer of value -1. This means that all the 32-bit are set to 1 (the two-complement encoding of -1 in 32 bits). Then it is cast to the typechar
which is an unsigned 16-bit value, so you get 16 bits set to one, which has the value 65535.(int) (char) (byte) -1
by explicitly casting it again to a 32-bit integer, you make sure that it is printed as a number instead of the character with the codepoint 65535.
这篇关于连续多次演员不按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文