Have you ever wanted to convert a hex string to an integer or convert an integer to a hex string? Java makes this conversion a simple process. This Java tutorial shows you how.**Hex String to an Integer **

In the Integer class, the parseInt() method provides a way to convert a string to int. In the parseInt() method, you can specify the radix value. For hex numbers, the radix would be 16.

String hex = "2A"; //The answer is 42

int intValue = Integer.parseInt(hex, 16);

**Integer to Hex String**

Now that you have converted it to an integer, lets now convert the int value back to a hex string. Again, Java makes this extremely easy.

String hex = Integer.toHexString(42);

**Summary**

Java makes it easy to convert between integers and string representations of numbers. Using the additional methods of toOctalString() or toBinaryString(), you can also convert to additional number formats.

## 13 comments:

Thanks! This was

veryhelpful!That was very helpful, but you still might want to mention that if you're using hexadecimal notations, sometimes they can use only one zero instead of two, which will confuse some things, so I just use this:

if(hex.length()<2){

hex="0"+hex;

}

That way the output code will be 00 if it is just 0.

Thank you!!

Thanks dear .It helped.

thank you!

Tyvm.

:-)

Very helpful indeed.. Thanks..

Muchas Gracias! super Ăștil thanks!

I must admit google does not find this one easily...thank you very much for the help!~

Very nice description of an annoying topic, lots of bad examples out there, so this is refreshing

hi, can you help me?

i have String MyHex="0x800000009";

how can i get the integer value from MyHex variable?

You may want to use Integer.decode() also keeping in mind that it will throw an exception if the Hex evaluates to a negative integer so watch out for anything above 0x7FFFFFFF

For the last comment: you have one 0 too many in your string MyHex (myHex), it should read 0x80000009 and for my suggestion you may want to stick to 0x7FFFFFF9

"The sequence of characters following an (optional) negative sign and/or radix specifier ("0x", "0X", "#", or leading zero) [...] must represent a positive value"

0x0 through 0x7FFFFFFF are positive integers (from 0 to Integer.MAX_VALUE).

0x8000000 through 0xFFFFFFFF are negative integers (from Integer.MIN_VALUE to -1)

how can i fix in the .xml file the value 0xff000000 and then used it as a int color?

## Post a Comment