在 Java 中将字符转换为整数 [英] Converting Chars to Ints in Java

查看:35
本文介绍了在 Java 中将字符转换为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

系统:Windows Vista 32 位,Java 6.0.2

System: Windows Vista 32-bit, Java 6.0.2

我有几个关于将字符转换为整数的问题.我运行下面的代码,将 myInt 的值为 4:

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';

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

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

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

Is this occuring because Java is automatically casting (anotherInt + '0') to an int, as in the first example? Thank you.

推荐答案

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."

这篇关于在 Java 中将字符转换为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆