Convert hex string to int

Roloc picture Roloc · Jun 25, 2012 · Viewed 190.1k times · Source

I am trying to convert a string that is 8 characters long of hex code into an integer so that I can do int comparison instead of string comparisons over a lot of different values.

I know this is fairly trivial in C++ but I need to do it in Java. The test case I need to satisfy is essentially to Convert "AA0F245C" to int and then back to that string so that I know it is converting right.

I have tried the following:

int decode = Integer.decode("0xAA0F245C");  // NumberFormatException
int decode2 = Integer.decode("AA0F245C"); //NumberFormatException
int parseInt = Integer.parseInt("AA0F245C", 16); //NumberFormatException
int valueOf = Integer.valueOf("AA0F245C", 16); //NumberFormatException

I have also tried doing it two characters at a time and multiplying the results, which the conversion works but the number is not right.

int id = 0;
for (int h = 0; h < hex.length(); h= h+2)
{
    String sub = hex.subSequence(h, h+2).toString();

if (id == 0)
    id = Integer.valueOf(sub, 16);
else
    id *= Integer.valueOf(sub, 16);             
 }
//ID = 8445600 which = 80DEA0 if I convert it back. 

I can not use third party libraries just so you know, so this has to be done in Java standard libraries.

Thank you for your help in advance.

Answer

Denys S&#233;guret picture Denys Séguret · Jun 25, 2012

It's simply too big for an int (which is 4 bytes and signed).

Use

Long.parseLong("AA0F245C", 16);