Convert a Hex String to an Integer and Back Again in Java
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 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.

2 comments:
Thanks! This was very helpful!
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.
Post a Comment