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.

Download Code

 
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.

Download Code

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:

Download Code

 
Alternatively, we can use the Long.toHexString() function, which converts a long value to a hex string.

Download Code

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.

Download Code

 
To convert the hexadecimal value to uppercase, replace x with X.

Download Code

 
Additionally, we can prepend the hexadecimal string with the radix indicator (0x or 0X) with the # flag.

Download Code

That’s all about converting Int to a Hex String in Kotlin.