[英]Why do I get a NumberFormatException with this Integer.parseInt(x, y)?
My code is simply: 我的代码很简单:
int idec = Integer.parseInt(value, 16);
When I enter as value "01dae610", I correctly get "31122960". 当我输入值“01dae610”时,我正确地得到“31122960”。 When I enter as value "d149e510", I get a java.lang.NumberFormatException.
当我输入值“d149e510”时,我得到一个java.lang.NumberFormatException。 The correct value is: "3511280912".
正确的值是:“3511280912”。
I have no clue why this is. 我不知道为什么会这样。 Can someone help?
有人可以帮忙吗?
Because that is outside the range of an int
. 因为那超出了
int
的范围。 Use a long
/ Long
instead. 请改用
long
/ Long
。
int
is signed in Java - so the maximum value is 2 31 - 1. int
是用Java 签名的 - 所以最大值是2 31 - 1。
If you use Long.parseLong(value, 16)
you'll get your desired value. 如果使用
Long.parseLong(value, 16)
您将获得所需的值。 You can then cast back to int
if you're happy to get the right bit pattern, but interpreted as a negative value instead. 如果您乐意获得正确的位模式,则可以转换回
int
,但会将其解释为负值。
Simply because it's the outside the range of int
. 仅仅因为它超出了
int
的范围。 You should use the long
data type instead. 您应该使用
long
数据类型。
Integer.MAX_VALUE
is 2147483647, which is lower than the value you are expecting. Integer.MAX_VALUE
是2147483647,低于您期望的值。 So this string doesn't represent anything which can be parsed into an int
. 所以这个字符串不代表任何可以解析成
int
。 Hence the exception. 因此例外。
The int data type is a 32-bit signed two's complement integer.
int数据类型是32位带符号的二进制补码整数。 It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).
它的最小值为-2,147,483,648,最大值为2,147,483,647(含)。
3,511,280,912 > 2,147,483,647, which explains the NumberFormatException
. 3,511,280,912> 2,147,483,647,它解释了
NumberFormatException
。
However, you could use a long
. 但是,你可以使用很
long
。 From that same page: 从同一页面:
The long data type is a 64-bit signed two's complement integer.
长数据类型是64位带符号的二进制补码整数。 It has a minimum value of -9,223,372,036,854,775,808 and a maximum value of 9,223,372,036,854,775,807 (inclusive).
它的最小值为-9,223,372,036,854,775,808,最大值为9,223,372,036,854,775,807(含)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.