[英]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.