在 Java 中将字符转换为整数
系统:Windows Vista 32位,Java 6.0.2
我有一些关于将字符转换为整数的问题。 我运行下面的代码,将 myInt 的值保留为 4:
char myChar = '4';
int myInt = myChar - '0';
现在,这种转换是 Java 自动执行的吗?是否从ascii“4”中减去ascii值“0”,然后在幕后转换为int?这让我很困惑,因为当我尝试反向操作时,我实际上必须将结果转换为 char:
int anotherInt = 5;
char newChar = anotherInt + '0'; //gives error
char newChar = (char)(anotherInt + '0'); //works fine
发生这种情况是因为 Java 自动将 (anotherInt + '0') 转换为 int,如第一个示例中所示?谢谢。
System: Windows Vista 32-bit, Java 6.0.2
I have a few questions about converting chars to ints.
I run the code below, leaving myInt with a value of 4:
char myChar = '4';
int myInt = myChar - '0';
Now, is this conversion something that Java does automatically? Was the ascii value of '0' subtracted from ascii '4', and then cast to an int behind the scenes? This is confusing for me because when I try to the reverse operation, I have to actually cast the result as a char:
int anotherInt = 5;
char newChar = anotherInt + '0'; //gives error
char newChar = (char)(anotherInt + '0'); //works fine
Is this occuring because Java is automatically casting (anotherInt + '0') to an int, as in the first example? Thank you.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从
char
(2 字节类型)到int
(4 字节类型)的转换在 Java 中是隐式的,因为这是一个扩大转换——所有您可以将可能的值存储在char
中,也可以将其存储在int
中。反向转换不是隐式的,因为它是缩小转换——它可能会丢失信息(int
的高两个字节被丢弃)。在这种情况下,您必须始终显式强制转换,作为告诉编译器“是的,我知道这可能会丢失信息,但我仍然想这样做”的一种方式。The conversion from
char
(a 2-byte type) toint
(a 4-byte type) is implicit in Java, because this is a widening conversion -- all of the possible values you can store in achar
you can also store in anint
. The reverse conversion is not implicit because it is a narrowing conversion -- it can lose information (the upper two bytes of theint
are discarded). You must always explicitly cast in such scenarios, as a way of telling the compiler "yes, I know this may lose information, but I still want to do it."如果遵循 C 规则,则在第一个示例中,您的 char 可以自动强制转换为 int,而无需进行强制转换,因为转换不会丢失信息。
但是,在第二种情况下需要显式转换,因为 char 小于 int,因此可能会丢失信息。
If C rules are anything to go by, your char can be automatically coerced into an int without a cast in your first example, as the conversion does not involve a loss of information.
However, an explicit cast is required in your second case, where there is potential to lose information since a char is smaller than an int.