numeric type parse functions exception with negative numbers
Asked Answered
I

2

5
System.out.println(Integer.parseInt("7FFFFFFF", 16)); //this is ok.
System.out.println(Integer.parseInt("FFFFFFFF", 16)); //this throws Exception
System.out.println(Integer.valueOf("FFFFFFFF", 16)); //this throws Exception

When I try to convert hexadecimal number to integer type, negative numbers with parseInt or valueOf methods, the method throws NumberFormatException for negative numbers. I couldn't find the answer anywhere.

Idellaidelle answered 24/3, 2020 at 10:17 Comment(1)
FFFFFFFF is out of range of Integer I think.Deprive
P
5

Integer.parseInt() and Integer.valueOf() expect the minus sign (-) for negative values.

Hence "FFFFFFFF" is parsed as a positive value, which is larger than Integer.MAX_VALUE. Hence the exception.

If you want to parse it as a negative value, parse it as long and cast to int:

System.out.println((int)Long.parseLong("FFFFFFFF", 16));

prints

-1
Priapic answered 24/3, 2020 at 10:23 Comment(0)
S
2

Integer.parseInt("FFFFFFFF", 16) doesn't mean "give me the int with this hexadecimal bit pattern". It means "interpret FFFFFFFF as a base-16 representation of a number, and give me an int representing the same number".

That number is the positive number 4294967295, which is out of range for an int, hence the exception.

Seljuk answered 24/3, 2020 at 10:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.