Integer.parseInt() doesn't parse large negative numbers

3

Why is NumberFormatException is thrown when i try Integer.parseInt("80000010", 16)?? That IS a 32-bit number, which is the size of java's int.

EDIT: The best part is this...

int z = 0x80000010;
System.err.println("equal to " + z);

Prints -2147483632 which is indeed 0x80000010 according to my calculator ;)

java
asked on Stack Overflow Mar 30, 2011 by Saideira • edited Mar 30, 2011 by Saideira

6 Answers

10

Because parseInt "parses the string argument as a signed integer", as specified in the API documentation. The value 80000010 with radix 16 is outside the valid range for a signed 32 byte value.

answered on Stack Overflow Mar 30, 2011 by jarnbjo
6

You can do

int value = (int) Long.parseLong("80000010", 16)

Update:

With Java 8 update (2014) you can write

int value = Integer.parseUnsignedInt("80000010", 16);
answered on Stack Overflow Mar 30, 2011 by Peter Lawrey • edited Jul 21, 2014 by kajacx
4

80,00,00,1016 = 2,147,483,66410

Whilst a Java integer has a range of -2,147,483,64810 to 2,147,483,64710.

answered on Stack Overflow Mar 30, 2011 by Paul Ruane
2

For those stuck with Java <= 7, Guava provides a utility for parsing ints as unsigned:

UnsignedInts.parseUnsignedInt("ffffffff", 16);
> -1
answered on Stack Overflow Jun 8, 2015 by Natix
1

It is because the first parameter is signed integer, so for negative numbers you have to give minus sign explicitly. And in your case you have big unsgined number outside the integer range.

answered on Stack Overflow Mar 30, 2011 by xappymah • edited Mar 30, 2011 by xappymah
1

You're parsing it with base 16. So it is greater than the maximum for integer.

answered on Stack Overflow Mar 30, 2011 by Riccardo Cossu

User contributions licensed under CC BY-SA 3.0