This article explores different ways to convert a hex string to an integer in Kotlin.

1. Using toInt() function

The Integer class contains several functions to convert the hex string (up to 0x7FFFFFFF) to an integer:

1. The Integer.decode() function takes a hexadecimal string preceded with the radix specifier (0x/0X) and decodes it into an integer.

Download Code

 
2. The String.toInt() function parse a string as an integer in the specified radix.

Download Code

 
3. The Integer.valueOf() function parse a string as a signed integer in the specified radix.

Download Code

2. Using toLong() function

All the above functions cannot parse a hexadecimal value greater than 0x7FFFFFFF (Int.MAX_VALUE in numeric). To handle large hexadecimal values up to 0x7FFFFFFFFFFFFFFF (Long.MAX_VALUE in numeric), use Long.decode() function instead.

Download Code

 
Alternately, use the String.toLong() function to parse a string as a long in the specified radix.

Download Code

3. Using BigInteger class

To handle even larger numbers than 0x7FFFFFFFFFFFFFFF, consider using BigInteger, whose constructor translates the hexadecimal string into a BigInteger in the given radix.

Download Code

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