Search code examples
javaintegerhexunsigned-integer

Converting a negative number created by toHexString back to an int in Java


I am getting an error because of the following line of code:

int x = color(Integer.parseInt("ffffffde",16));

The value "ffffffde" is being created by the following code:

Integer.toHexString(int_val);

Error:

Exception in thread "Animation Thread" java.lang.NumberFormatException: For input string: "ffffffde"
    at java.lang.NumberFormatException.forInputString(Unknown Source)
    at java.lang.Integer.parseInt(Unknown Source)

I think it might be because it is a negative value.

Any ideas why or how or how to fix it?


Edit:

Turns out it is a known bug JDK-4215269 in versions of Java prior to 8.

Although you can convert integers to hex strings, you cannot convert them back if they are negative numbers!


Solution

  • ffffffde is bigger than integer max value

    Java int is 32 bit signed type ranges from –2,147,483,648 to 2,147,483,647.

    ffffffde = 4,294,967,262 
    

    Edit

    You used Integer.toHexString(int_val) to turn a int into a hex string. From the doc of that method:

    Returns a string representation of the integer argument as an unsigned integer in base 16.

    But int is a signed type.

    USE

    int value = new BigInteger("ffffffde", 16).intValue();
    

    to get it back as a negative value.