Home > DeveloperSection > Forums > How to convert int to hex in java?
Goti Bandu

Total Post:119

Posted on    October-16-2014 12:30 AM

 Java Java  OOPS 

 1 Reply(s)
 697  View(s)
Rate this:
I have the following code.

int Val = -32768;

String Hex = Integer.toHexString(Val);

This equates to ffff8000.

int FirstAttempt = Integer.parseInt(Hex, 16); // Error "Invalid Int"

int SecondAttempt = Integer.decode("0x" + Hex);  // Error "Invalid Int"

So, initially, it converts the value -32768 into a hex string ffff8000, but then it can't convert the hex string back into an Integer.

In .Net it works as I'd expect, and returns -32768.

I know that I could write my own little method to convert this myself, but I'm just wondering if I'm missing something, or if this is genuinely a bug?

Ashish Pandey

Total Post:128

Posted on    October-16-2014 12:31 AM

It overflows, because the number is negative.

Try this and it will work:

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

Modified On Apr-20-2016 01:38:24 AM

Don't want to miss updates? Please click the below button!

Follow MindStick