Authors Top

If you have a few years of experience with the Kotlin language and server-side development, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

1. Overview

In this quick tutorial, we’ll get familiar with a few ways to convert integers to their corresponding hexadecimal values.

2. Integer.toHexString()

The simplest way to convert an integer to its corresponding hexadecimal form is to use the Integer.toHexString(int) method:

val hex = Integer.toHexString(4001)
assertEquals("fa1", hex)

As shown above, the toHexString() method generates the hex value as expected. It’s worth mentioning that this method will convert negative numbers to their unsigned values under the hood.

3. The toString() Extension Function

As of Kotlin 1.1, we can use the toString(radix: Int) extension function on integers to convert them to hex values:

val number = 4001
assertEquals("fa1", number.toString(16))

As shown above, this function accepts the base or radix number as its argument. Obviously, we’re passing 16 to ask for hexadecimal values.

Interestingly, there is a subtle difference between Integer.toHexString() and toString() on unsigned conversion. More specifically, the former first converts the integer to its unsigned equivalent. So, for negative numbers, they return different values:

val number = -100
assertNotEquals(Integer.toHexString(number), number.toString(16))

To fix this, we can convert the integer to its unsigned long equivalent before calling toString():

assertEquals(Integer.toHexString(number), number.toUInt().toString(16))

As shown above, we’re using the unsigned integer feature introduced in Kotlin 1.3 for unsigned conversion.

Alternatively, we can perform a bitwise and operation with“0xffffffffL” to convert the integer to its unsigned long form:

val unsignedLong = number.toLong() and 0xffffffffL
assertEquals(Integer.toHexString(number), unsignedLong.toString(16))

This can be useful, especially when the toUInt() isn’t available as an option.

4. Format Specifiers

In addition to the above approaches, we can also use the format() extension function for this conversion. To do that, we have to call the format() method with the “%x” format specifier:

val number = 4001
assertEquals("fa1", "%x".format(number))

The “%x” specifier will convert the given numbers to their hexadecimal forms.

5. Conclusion

In this tutorial, we learned a few approaches to convert integers to their corresponding hexadecimal strings.

As usual, all the examples are available over on GitHub.

Authors Bottom

If you have a few years of experience with the Kotlin language and server-side development, and you’re interested in sharing that experience with the community, have a look at our Contribution Guidelines.

Comments are closed on this article!