说我有这个字符串0xdadacafe
(显然比Integer.MAX_VALUE:0x7fffffff
大)。如果使用Integer.parseInt(String, int)
进行解析,则会得到一个NumberFormatException
。有什么方法可以解析此字符串并获得“静默”溢出?
换句话说,有什么方法可以解析此字符串并获取-623195394
,这是您执行System.out.println(0xdadacafe);
时所获得的值
(而且我可能不想做类似(int)Long.parseLong(String, int)
的事情)
谢谢
最佳答案
您可以将其读为BigInteger,然后返回正确的int值。
BigInteger value = new BigInteger("dadacafe", 16); // 3671771902
value.intValue(); // -623195394
编辑:
回复:评论说这很慢。
我的意思是there's always this right:
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溢出确实是真的,那可能不会比这更好。