How to convert Int to Hex String in Kotlin?

NumbersIntegerIntHexKotlin

Numbers Problem Overview


I'm looking for a similar function to Java's Integer.toHexString() in Kotlin. Is there something built-in, or we have to manually write a function to convert Int to String?

Numbers Solutions


Solution 1 - Numbers

You can still use the Java conversion by calling the static function on java.lang.Integer:

val hexString = java.lang.Integer.toHexString(i)

And, starting with Kotlin 1.1, there is a function in the Kotlin standard library that does the conversion, too:

> fun Int.toString(radix: Int): String > > Returns a string representation of this Int value in the specified radix.

Note, however, that this will still be different from Integer.toHexString(), because the latter performs the unsigned conversion:

println((-50).toString(16)) // -32
println(Integer.toHexString(-50)) // ffffffce

But with experimental Kotlin unsigned types, it is now possible to get the same result from negative number unsigned conversion as with Integer.toHexString(-50):

println((-50).toUInt().toString(16)) // ffffffce

Solution 2 - Numbers

You can simply do it like this: "%x".format(1234)

Solution 3 - Numbers

If you need to add zero before bytes which less than 10(hex), for example you need string - "0E" then use: "%02x".format(14)

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmilosmnsView Question on Stackoverflow
Solution 1 - NumbershotkeyView Answer on Stackoverflow
Solution 2 - NumbersM.SameerView Answer on Stackoverflow
Solution 3 - NumbersArtem BotnevView Answer on Stackoverflow