Java converting int to hex and back again

It overflows, because the number is negative.

Try this and it will work:

int n = (int) Long.parseLong("ffff8000", 16);

  • int to Hex :

    Integer.toHexString(intValue);
    
  • Hex to int :

    Integer.valueOf(hexString, 16).intValue();
    

You may also want to use long instead of int (if the value does not fit the int bounds):

  • Hex to long:

    Long.valueOf(hexString, 16).longValue()
    
  • long to Hex

    Long.toHexString(longValue)
    

It's worth mentioning that Java 8 has the methods Integer.parseUnsignedInt and Long.parseUnsignedLong that does what you wanted, specifically:

Integer.parseUnsignedInt("ffff8000",16) == -32768

The name is a bit confusing, as it parses a signed integer from a hex string, but it does the work.


int val = -32768;
String hex = Integer.toHexString(val);

int parsedResult = (int) Long.parseLong(hex, 16);
System.out.println(parsedResult);

That's how you can do it.

The reason why it doesn't work your way: Integer.parseInt takes a signed int, while toHexString produces an unsigned result. So if you insert something higher than 0x7FFFFFF, an error will be thrown automatically. If you parse it as long instead, it will still be signed. But when you cast it back to int, it will overflow to the correct value.

Tags:

Hex

Java

String