[英]Parse integer string (larger than Integer.MAX_VALUE)
說我有這個字符串0xdadacafe
(明顯大於Integer.MAX_VALUE: 0x7fffffff
)。 如果我使用Integer.parseInt(String, int)
進行解析,則會得到NumberFormatException
。 有什么方法可以解析此字符串並獲得“靜默”溢出?
換句話說,有什么方法可以解析此字符串並獲取-623195394
,這是您執行System.out.println(0xdadacafe);
獲得的值System.out.println(0xdadacafe);
(而且我可能不想做類似(int)Long.parseLong(String, int)
事情)
謝謝
您可以將其讀取為BigInteger ,然后返回正確的int值。
BigInteger value = new BigInteger("dadacafe", 16); // 3671771902
value.intValue(); // -623195394
編輯:
回復:評論說這很慢。
我的意思是, 總有這種權利 :
public static int parseInt(String s, int radix)
throws NumberFormatException
{
if (s == null) {
throw new NumberFormatException("null");
}
if (radix < Character.MIN_RADIX) {
throw new NumberFormatException("radix " + radix +
" less than Character.MIN_RADIX");
}
if (radix > Character.MAX_RADIX) {
throw new NumberFormatException("radix " + radix +
" greater than Character.MAX_RADIX");
}
int result = 0;
boolean negative = false;
int i = 0, len = s.length();
int digit;
if (len > 0) {
char firstChar = s.charAt(0);
if (firstChar < '0') { // Possible leading "-"
if (firstChar == '-') {
negative = true;
} else
throw new NumberFormatException(s);
if (len == 1) // Cannot have lone "-"
throw new NumberFormatException(s);
i++;
}
while (i < len) {
// Accumulating negatively avoids surprises near MAX_VALUE
digit = Character.digit(s.charAt(i++),radix);
if (digit < 0) {
throw new NumberFormatException(s);
}
result *= radix;
result -= digit;
}
} else {
throw new NumberFormatException(s);
}
return negative ? result : -result;
}
但是在這一點上,我會開始認為這可能無法正確解決問題。 我不確定您是否正在准備使用現有軟件,或者情況可能是什么,但是如果您真正需要“按時快速” int溢出確實是真的,它可能不會比這更好。
嘗試
int i = (int)Long.parseLong("0xdadacafe".substring(2), 16);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.