为什么这个 Java parseInt 十六进制字符串会导致 NumberFormatException?
Integer.parseInt("ff8ca87c", 16);
由于某种原因,这给了我一个 NumberFormatException 。你知道这是为什么吗?
Exception in thread "main" java.lang.NumberFormatException: For input string: "ff8ca87c"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
Integer.parseInt("ff8ca87c", 16);
This gives me a NumberFormatException for some reason. Do you know why that is?
Exception in thread "main" java.lang.NumberFormatException: For input string: "ff8ca87c"
at java.lang.NumberFormatException.forInputString(Unknown Source)
at java.lang.Integer.parseInt(Unknown Source)
at java.lang.Integer.valueOf(Unknown Source)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
它失败的原因是您试图将 +0xff8ca87c 放入有符号整数中。 32 位有符号整数的最大值为 +0x7ffffffff,因为最高有效位用于存储符号。
尝试使用
long
代替。 64 位有符号 int 的最大值为0x7fffffffffffffff
,在这种情况下这足以满足您的需求。或者,在 Java 8 中,您可以使用
Integer.parseUnsignedInt("ff8ca87c", 16);
,它将将该值视为无符号整数。The reason it fails is that you're trying to put
+0xff8ca87c
into a signed integer. The maximum value of a 32-bit signed integer is+0x7fffffff
, because the most significant bit is used to store the sign.Try using a
long
instead. The maximum value of a 64-bit signed int is0x7fffffffffffffff
, which is more than adequate for your needs in this case.Or, in Java 8 you can use
Integer.parseUnsignedInt("ff8ca87c", 16);
which will treat the value as an unsigned integer.