Why can't this 4-byte hex number be converted into an int?

322 Views Asked by At

I am looking to create a java method that takes a 4-byte signed hex number and convert it into an int. However, when I test inputs such as "aaaaaaaa" or "ffffffff"

Integer.valueOf("aaaaaaaa", 16)
Integer.valueOf("ffffffff", 16)

which should give the values: -1431655766 and -1 respectively.

However, I am getting the following exception

Exception in thread "main" java.lang.NumberFormatException: For input string: "ffffffff"
    at java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
    at java.lang.Integer.parseInt(Integer.java:583)
    at java.lang.Integer.valueOf(Integer.java:740)
    at ByteTest.main(ByteTest.java:8)

What can I do to fix this?

1

There are 1 best solutions below

0
On

From the JavaDoc...

Returns an Integer object holding the value extracted from the specified String when parsed with the radix given by the second argument. The first argument is interpreted as representing a signed integer in the radix specified by the second argument, exactly as if the arguments were given to the parseInt(String, int) method.

An Integer can't hold a positive equivalent of a eight digit hexadecimal value.