[英]Converting Hex in Java, wrong value with negative values
我已经看到关于主题中提到的主题的几个问题(例如这个),但在我看来,他们都没有提供这个例子。 我正在使用 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 内,当我有负数时它也会失败。例如
带有十六进制0xc0f1a47ba0c04d89
的String
用于Long
数-4,543,669,698,155,229,815
返回:
java.lang.NumberFormatException: For input string: "c0f1a47ba0c04d89"
如何修复脚本以获得所需的行为?
Long.decode
和Integer.decode
不接受补充值,例如Integer.toHexString
返回的值:符号应表示为前导-
如javadoc 中的 DecodableString 语法所述。
跟随可选符号和/或基数说明符(“0x”、“0X”、“#”或前导零)的字符序列被 Long.parseLong 方法解析为具有指示的基数(10、16 或 8 )。 此字符序列必须表示正值,否则将抛出 NumberFormatException。 如果指定 String 的第一个字符是减号,则结果是否定的
如果您可以更改输入String
的格式,则使用Integer.toString(value, 16)
而不是Integer.toHexString(value)
生成它。
如果您可以切换到 Java 8,请使用parseUnsignedInt/Long 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.