Convert hex string to integer in Kotlin
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.
|
1 2 3 4 5 6 7 |
fun main() { val hex = "0x7FFFFFFF" // with radix specifier val decimal = Integer.decode(hex) println(decimal) // 2147483647 } |
2. The String.toInt() function parse a string as an integer in the specified radix.
|
1 2 3 4 5 6 7 |
fun main() { val hex = "7FFFFFFF" val decimal: Int = hex.toInt(16) println(decimal) // 2147483647 } |
3. The Integer.valueOf() function parse a string as a signed integer in the specified radix.
|
1 2 3 4 5 6 7 |
fun main() { val hex = "7FFFFFFF" val decimal = Integer.valueOf(hex, 16) println(decimal) // 2147483647 } |
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.
|
1 2 3 4 5 6 7 |
fun main() { val hex = "0x7FFFFFFFFFFFFFF" // with radix specifier val decimal = java.lang.Long.decode(hex) println(decimal) // 576460752303423487 } |
Alternately, use the String.toLong() function to parse a string as a long in the specified radix.
|
1 2 3 4 5 6 7 |
fun main() { val hex = "7FFFFFFFFFFFFFF" val decimal = hex.toLong(16) println(decimal) // 576460752303423487 } |
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.
|
1 2 3 4 5 6 7 8 9 |
import java.math.BigInteger fun main() { val hex = "7FFFFFFFFFFFFFFFFFFFFF" val decimal = BigInteger(hex, 16) println(decimal) // 154742504910672534362390527 } |
That’s all about converting a hex string to an integer in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)