gpt4 book ai didi

java - 将 Java 十六进制转换为十进制时出现错误

转载 作者:太空宇宙 更新时间:2023-11-04 10:03:39 27 4
gpt4 key购买 nike

System.out.println ("Hex fun:" + Long.toHexString (0x100000000L + 0xcafebabe));

我有上面的代码,

在Java中,如果操作数数据类型不同,

不进行扩大转换。

long a = 10;
int b = 2;

a + b -> b 转换为 long 类型。

那边

十六进制0xcafebabe -> 32位int,因为左操作数是logn类型,所以被扩展并转换为符号。显示错误的操作值。是的,这很好。

问题是,如果你采用十进制数,

System.out.println (Integer.toHexString (-889275714)); // cafebabe
System.out.println (Long.toHexString (3405691582L)); // cafebabe -> extended

System.out.println (Integer.parseUnsignedInt ("cafebabe", 16)); // 3405691582 (QWORD)

Integer.decode(“0xcafebabe”)导致错误。

我遇到了 NumberFormat 异常,但我不知道为什么。

System.out.println(Integer.parseUnsignedInt("cafebabe", 16)); -> 这就是我处理它的方式,这样我就可以输出带符号的 32 位十进制整数。

据我所知,Java原语不会根据操作系统减少数据类型的长度。测试环境在 64 位 Windows 上运行。

JDK 版本为 8。

最佳答案

来自 documentation :

This sequence of characters must represent a positive value or a NumberFormatException will be thrown.

您有overflow整数和负数提交给解码方法。因为Integer.MAX_VALUE == 21474836470xcafebabe == 3405691582 .

针对您的情况的解决方案之一是使用 Long.decode() :

System.out.println ("Hex fun: " + Long.toHexString (0x100000000L + Long.decode ("0xcafebabe")));
// output: Hex fun: 1cafebabe
<小时/>

更新:
要了解到底发生了什么,您需要练习调试或阅读源代码:

public static Integer decode(String nm) throws NumberFormatException {
// some code
result = Integer.valueOf(nm.substring(index), radix);
// in our case Integer.valueOf("cafebabe", 16)
// some code
}

public static Integer valueOf(String s, int radix) throws NumberFormatException {
return Integer.valueOf(parseInt(s,radix));
}

public static int parseInt(String s, int radix) throws NumberFormatException {
// some code
// limit == -Integer.MAX_VALUE == -2147483647
// multmin == -134217727
int multmin = limit / radix;
int result = 0;
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
int digit = Character.digit(s.charAt(i++), radix);
if (digit < 0 || result < multmin) {
throw NumberFormatException.forInputString(s);
}
result *= radix;
if (result < limit + digit) {
throw NumberFormatException.forInputString(s);
}
result -= digit;
}
// some code
}

result < multmin防止整数溢出。在最后一次迭代中 i == 7我们将最后一个数字解码为 digit == 14result == -212855723 。它们相乘的结果会溢出int。为了防止这种情况发生,我们在乘法之前设置最小值 multmin == limit / radix在我们的例子中radix == 16 .

关于java - 将 Java 十六进制转换为十进制时出现错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53200473/

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