开发者

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

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 ;)


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.


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);


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.


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

UnsignedInts.parseUnsignedInt("ffffffff", 16);
> -1


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


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.


Integer.parseInt() takes in a signed integer as it's input. This means the input has to be between "7FFFFFFF" and "-80000000". Note the negative sign before 0x80000000. The input you want for -2147483632 is the positive 2147483632 (0x7FFFFFF0) with a negative sign in front, so Integer.parseInt("-7FFFFFF0", 16).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜