This post will discuss how to convert a hex string to an integer in Java.

1. Using Integer class

The Integer class provides several utility functions to convert a hex string to an integer in Java. You may use the Integer.decode() method to decode a String into an Integer. It accepts a hexadecimal number preceded with the radix specifier 0x or 0X, otherwise a NumberFormatException will be thrown.

Download  Run Code

 
Alternatively, you can use the Integer.parseInt() method to parse a string as a signed integer in the specified radix. Following is a simple example demonstrating usage of this:

Download  Run Code

 
The Integer.valueOf() method is a wrapper over the Integer.parseInt() method, but it returns an Integer instead of a primitive int.

Download  Run Code

2. Using Long class

All the above methods in Integer class fails for numbers greater than Integer.MAX_VALUE. That means it cannot parse a hexadecimal value greater than 0x7FFFFFFF. You should use Long.decode() method instead that can handle large numbers up to Long.MAX_VALUE (i.e., 0x7FFFFFFFFFFFFFFF in hexadecimal).

Download  Run Code

 
As with the Integer class, you may use Long.parseLong() or Long.valueOf() method:

Download  Run Code

3. Using BigInteger class

For even bigger numbers than 0x7FFFFFFFFFFFFFFF (Long.MAX_VALUE), you may use the BigInteger class. The BigInteger constructor translates the specified value in the specified radix into a BigInteger.

Download  Run Code

That’s all about converting a hex string to an integer in Java.