在 Java 中将字符转换为整数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4221225/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 05:22:38  来源:igfitidea点击:

Converting Chars to Ints in Java

javacharintcasting

提问by worker1138

System: Windows Vista 32-bit, Java 6.0.2

系统:Windows Vista 32 位,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:

我有几个关于将字符转换为整数的问题。我运行下面的代码,将 myInt 的值为 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:

现在,这种转换是 Java 自动完成的吗?是从 ascii '4' 中减去 '0' 的 ascii 值,然后在幕后转换为 int 吗?这让我感到困惑,因为当我尝试反向操作时,我必须将结果实际转换为字符:

  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.

这是因为 Java 自动将 (anotherInt + '0') 转换为 int,如第一个示例所示?谢谢你。

回答by cdhowie

The conversion from char(a 2-byte type) to int(a 4-byte type) is implicit in Java, because this is a widening conversion -- all of the possible values you can store in a charyou can also store in an int. The reverse conversion is not implicit because it is a narrowing conversion -- it can lose information (the upper two bytes of the intare 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."

从转换char(2字节型)到int(4字节型)是在Java中隐含的,因为这是一个扩大转换-你可以在商店可能值char还可以存储在一个int。反向转换不是隐式的,因为它是一种收缩转换——它可能会丢失信息(int丢弃的高两个字节)。在这种情况下,您必须始终显式地强制转换,作为告诉编译器“是的,我知道这可能会丢失信息,但我仍然想这样做”的一种方式。

回答by Nathan Pitman

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.

如果需要遵循 C 规则,则在第一个示例中,您的 char 可以自动强制转换为 int 而不进行强制转换,因为转换不涉及信息丢失。

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.

但是,在第二种情况下需要显式转换,因为 char 小于 int,因此可能会丢失信息。