[英]Parse integer string (larger than Integer.MAX_VALUE)
Say I have this string 0xdadacafe
(which is obviously greater than Integer.MAX_VALUE: 0x7fffffff
). 说我有这个字符串
0xdadacafe
(明显大于Integer.MAX_VALUE: 0x7fffffff
)。 If I used Integer.parseInt(String, int)
to parse it, I would get a NumberFormatException
. 如果我使用
Integer.parseInt(String, int)
进行解析,则会得到NumberFormatException
。 Is there any way to parse this string and get a 'silent' overflow? 有什么方法可以解析此字符串并获得“静默”溢出?
In other words, is there any way to parse this string and get -623195394
, which is the value you'd get if you do System.out.println(0xdadacafe);
换句话说,有什么方法可以解析此字符串并获取
-623195394
,这是您执行System.out.println(0xdadacafe);
获得的值System.out.println(0xdadacafe);
(And I probably wouldn't want to do something like (int)Long.parseLong(String, int)
) (而且我可能不想做类似
(int)Long.parseLong(String, int)
事情)
Thanks 谢谢
You can read it in as a BigInteger and then return the correct int value. 您可以将其读取为BigInteger ,然后返回正确的int值。
BigInteger value = new BigInteger("dadacafe", 16); // 3671771902
value.intValue(); // -623195394
Edit: 编辑:
re: comments saying this is slow.. 回复:评论说这很慢。
I mean, 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;
}
But at this point, I would start to think that maybe this isn't solving the problem correctly. 但是在这一点上,我会开始认为这可能无法正确解决问题。 I'm not sure if you're railing up against existing software, or what the situation may be, but if 'fast-as-light' int overflows is actually something you truly need - it probably won't get much better than this.
我不确定您是否正在准备使用现有软件,或者情况可能是什么,但是如果您真正需要“按时快速” int溢出确实是真的,它可能不会比这更好。
尝试
int i = (int)Long.parseLong("0xdadacafe".substring(2), 16);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.