Convert Int to a Hex String in Kotlin
This article explores different ways to convert Int to a Hex String in Kotlin.
1. Using Int.toString() function
A simple solution to convert an integer to a hex string is using the toString() library function, which is overloaded to accept a radix. We call the toUpperCase() function on the resultant string, to get a hexadecimal value in uppercase.
|
1 2 3 4 5 6 |
fun main() { val intValue = 1000 val hex = intValue.toString(16) println(hex) // 3e8 println(hex.toUpperCase()) // 3E8 } |
Alternatively, we can invoke the toHexString() function of the Integer class, which converts an integer to a hex string. Note that it performs the unsigned conversion and handles numbers less than or equal to Int.MAX_VALUE.
|
1 2 3 4 5 |
fun main() { val intValue = 1000 val hex = Integer.toHexString(intValue) println(hex) // 3e8 } |
2. Using Long.toString() function
Both the above utility functions cannot produce a hexadecimal value greater than 0x7FFFFFFF. To parse numbers upto 0x7FFFFFFFFFFFFFFF (i.e., Long.MAX_VALUE), we can use the toString() function as shown below:
|
1 2 3 4 5 |
fun main() { val longValue = Long.MAX_VALUE val hex = longValue.toString(16) println(hex) // 7fffffffffffffff } |
Alternatively, we can use the Long.toHexString() function, which converts a long value to a hex string.
|
1 2 3 4 5 |
fun main() { val longValue = Long.MAX_VALUE val hex = java.lang.Long.toHexString(longValue) println(hex) // 7fffffffffffffff } |
3. Using String.format() function
Another plausible option is to call the String.format() function with the format string x, which formats an integer as a hexadecimal string.
|
1 2 3 4 5 |
fun main() { val intValue = Int.MAX_VALUE val hex = String.format("%x", intValue) println(hex) // 7fffffff } |
To convert the hexadecimal value to uppercase, replace x with X.
|
1 2 3 4 5 |
fun main() { val intValue = Int.MAX_VALUE val hex = String.format("%X", intValue) println(hex) // 7FFFFFFF } |
Additionally, we can prepend the hexadecimal string with the radix indicator (0x or 0X) with the # flag.
|
1 2 3 4 5 |
fun main() { val longValue = Long.MAX_VALUE val hex = String.format("%#X", longValue) println(hex) // 0X7FFFFFFFFFFFFFFF } |
That’s all about converting Int to a Hex String 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 :)