0

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?

  • As of Java 8+, use [`parseUnsignedInt()`](https://docs.oracle.com/javase/8/docs/api/java/lang/Integer.html#parseUnsignedInt-java.lang.String-int-), and the result of those two inputs will be `-1431655766` and `-1`. – Andreas Sep 16 '20 at 03:31

1 Answers1

0

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.

drkblog
  • 388
  • 2
  • 8