假设我有这个字符串0xdadacafe
(显然大于Integer.MAX_VALUE:0x7fffffff
)。如果我使用Integer.parseInt(String, int)
来解析它,我会得到NumberFormatException
。有没有办法解析这个字符串并获得“无声”溢出?
换句话说,是否有任何方法可以解析此字符串并获取-623195394
,这是您System.out.println(0xdadacafe);
(我可能不想做(int)Long.parseLong(String, int)
)
由于
答案 0 :(得分:3)
您可以将其作为BigInteger读取,然后返回正确的int值。
BigInteger value = new BigInteger("dadacafe", 16); // 3671771902
value.intValue(); // -623195394
修改强>
re:评论说这很慢..
我的意思是,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;
}
但是在这一点上,我会开始认为这可能不是正确解决问题。我不确定你是否会反对现有的软件,或者情况如何,但如果“快速轻微”的溢出实际上是你真正需要的东西 - 它可能不会比这更好
答案 1 :(得分:3)
试
int i = (int)Long.parseLong("0xdadacafe".substring(2), 16);