java - 整数如何自动将字符转换为ASCII值?

标签 java char integer ascii

当我执行 Integer.value Of('a') 时 它返回 97,即字符 a 的 ASCII 值。

我想知道 valueOf 方法中 char 何时转换为 ascii 值?

最佳答案

发生在你身上的是内部类型转换。

所以你的代码相当于这样:

char a = 'a';
int aint = (int)a;
Integer aInteger = Integer.valueOf(aint);
System.out.println(aInteger.toString());

引用oracle java教程:https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html

char: The char data type is a single 16-bit Unicode character. It has a minimum value of '\u0000' (or 0) and a maximum value of '\uffff' (or 65,535 inclusive).

因此变量 a 保存与字符“a”(97) 等效的 unicode

接下来发生的是扩大操作 https://docs.oracle.com/javase/specs/jls/se7/html/jls-5.html

5.1.2. Widening Primitive Conversion

[...]

A widening conversion of a char to an integral type T zero-extends the representation of the char value to fill the wider format.

因此您的 char(16 位)将被扩展为 int(32 位)。

这个 int 就是被输入到 Integer.valueOf() 中的内容

希望能回答您的问题。

托比

关于java - 整数如何自动将字符转换为ASCII值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45162300/

相关文章:

java - Java中从字符串中提取字符

objective-c - 如何在不实际更改的情况下重新排列 char* 的开头和结尾(索引方式)?

c++ - 整数作为 8 传递给函数,但函数内部的值是 -439854520

java - 写入长值以在 apache POI 中表现出色

java - 替换 <String, String[]> TreeMap 中的空值

转换要在 strcat 中使用的整数

java - 在 Java 中使用 EntityManager 返回计数 native 查询的结果?

java - 检查对象是否属于类型

java - 如何使用 Gson 将 Json 转换为 Java 对象

ios - 核心数据 integer32 与 integer64