在 Java 中将字符转换为整数

发布于 2024-10-03 06:03:32 字数 492 浏览 5 评论 0原文

系统: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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一百个冬季 2024-10-10 06:03:32

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

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 char you 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 int 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."

丶视觉 2024-10-10 06:03:32

如果遵循 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文