gpt4 book ai didi

java - Java 中是否有一种方法可以模拟将原始类型转换为 Character?

转载 作者:搜寻专家 更新时间:2023-11-01 02:38:07 25 4
gpt4 key购买 nike

为了简化一些字节码分析,我想通过调用装箱类型的等效方法来替换 Java 程序中原始类型的显式(向下)转换。在大多数情况下,这很简单:

double d = 42.0;
int i = (int)d;

可以变成

Double tmp = new Double(d);
int i = tmp.intValue();

这适用于所有签名类型。但是 charCharacter 没有这样的方法。也就是说,Integer、Float 等具有方法 intValuefloatValue 等,但没有一个具有方法 charValue。有没有jdk方法可以从原始类型到char/Character?

所以基本上,有没有这样的东西:

Integer num = new Integer(65);
char ch = num.charValue();

关键是不要使用(char)

最佳答案

如果你正在修改字节码,我认为你不需要转换为 char .在字节码中,char type 是二等公民,实际处理为 int .来自 JVMS §4.9.2 :

An instruction operating on values of type int is also permitted to operate on values of type boolean, byte, char, and short.

As noted in §2.3.4 and §2.11.1, the Java Virtual Machine internally converts values of types boolean, byte, short, and char to type int.)

所以虽然你不能,比如说,分配一个 intchar在没有显式转换的 Java 语言中,您可以在字节码中执行此操作,因为它们具有相同的“verification type”,即 int . char 的字节码表示只是一个 int恰好其高两个字节为零。所以不是:

char ch = num.charValue();

你将能够逃脱(在字节码中):

int ch = num.intValue() & 0x0000FFFF;

然后假装 chchar (例如,将其传递给需要 char 的方法或将其存储在 char 字段或数组中)。

但是,如果我理解正确的话,这就是 i2c 的意思intchar cast 指令已经这样做了,因此用显式 AND 操作替换它不会更简单。

It's also surprisingly hard to find what actually happens if you cast a (signed)double into an (unsigned)char.

当您从 float 转换时或 doublebyte , short , 或 char , 它首先转换为 int ,这会使超出范围的值饱和到 Integer.MAX_VALUEInteger.MIN_VALUE , 然后截断 int 的字节以适应最终类型。参见 JLS §5.1.3 – Narrowing Primitive Conversion .截断步骤意味着将超出范围的浮点值转换为 byte , short , 或 char可能不会给出有用的结果。

关于java - Java 中是否有一种方法可以模拟将原始类型转换为 Character?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41476617/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com