【发布时间】:2017-02-16 06:49:31
【问题描述】:
我已经看到关于主题中提到的主题的几个问题(例如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"
如何修复脚本以获得所需的行为?
【问题讨论】:
-
@Aaron,对不起,打字不好。我做
"0x"+Integer.toHexString(Integer.MIN_VALUE)。这也很糟糕吗?