简体   繁体   中英

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". When I enter as value "d149e510", I get a java.lang.NumberFormatException. The correct value is: "3511280912".

I have no clue why this is. Can someone help?

Because that is outside the range of an int . Use a long / Long instead.

int is signed in Java - so the maximum value is 2 31 - 1.

If you use Long.parseLong(value, 16) you'll get your desired value. You can then cast back to int if you're happy to get the right bit pattern, but interpreted as a negative value instead.

Simply because it's the outside the range of int . You should use the long data type instead.

Integer.MAX_VALUE is 2147483647, which is lower than the value you are expecting. So this string doesn't represent anything which can be parsed into an int . Hence the exception.

From here :

The int data type is a 32-bit signed two's complement integer. It has a minimum value of -2,147,483,648 and a maximum value of 2,147,483,647 (inclusive).

3,511,280,912 > 2,147,483,647, which explains the NumberFormatException .

However, you could use a long . From that same page:

The long data type is a 64-bit signed two's complement integer. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM