我已经看到关于主题中提到的主题的几个问题(例如 this one ),但在我看来,他们都没有提供这个例子。我正在使用 Java7,我想将表示十六进制或十进制的 String
转换为 Integer
或 Long
值(取决于它是什么代表),我执行以下操作:
public Number getIntegerOrLong(String num) {
try {
return Integer.decode(num);
} catch (NumberFormatException nf1) {
final long decodedLong = Long.decode(num);
if ((int) decodedLong == decodedLong) {//used in Java8 java.util.Math.toIntExact()
return (int) decodedLong;
}
return decodedLong;
}
}
当我使用表示十进制数的字符串时,一切正常,问题出在负十六进制数上
现在,如果我这样做:
String hex = "0x"+Integer.toHexString(Integer.MIN_VALUE);
Object number = getIntegerOrLong(hex);
assertTrue(number instanceof Integer):
失败,因为它返回一个 Long
。其他负整数值也是如此。
此外,当我像下面这样使用 Long.MIN_VALUE
时:
String hex = "0x"+Integer.toHexString(Long.MIN_VALUE);
Object number = getIntegerOrLong(hex);
assertTrue(number instanceof Long):
失败,因为 NumberFormatException
消息:
java.lang.NumberFormatException: For input string: "8000000000000000"
我还尝试使用其他随机 Long
值(因此在 Long.MIN_VALUE 和 Long.MAX_VALUE 内,当我有负数时它也会失败。例如
String
为 Long
数字 -4,543,669,698,155,229,815
的十六进制 0xc0f1a47ba0c04d89
返回:
java.lang.NumberFormatException: For input string: "c0f1a47ba0c04d89"
如何修复脚本以获得所需的行为?
最佳答案
Long.decode
和 Integer.decode
不接受由 Integer.toHexString
返回的补充值:符号应表示为前导 -
,如 javadoc 中的 DecodableString 语法所述.
The sequence of characters following an optional sign and/or radix specifier ("0x", "0X", "#", or leading zero) is parsed as by the Long.parseLong method with the indicated radix (10, 16, or 8). This sequence of characters must represent a positive value or a NumberFormatException will be thrown. The result is negated if first character of the specified String is the minus sign
如果您可以更改输入 String
的格式,则使用 Integer.toString(value, 16)
而不是 Integer.toHexString(value )
。
如果可以切换到 Java 8,请使用 parseUnsignedInt/Long .
关于java - 在 Java 中转换十六进制,错误值为负值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39914385/