Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert Int to Hex String in Kotlin?

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?

like image 375
milosmns Avatar asked Jan 14 '17 22:01

milosmns


People also ask

What is parseInt in Kotlin?

parseInt() function takes the string as argument and returns int value if conversion is successful. Else, it throws java. lang. NumberFormatException same as that of String.


2 Answers

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 
like image 164
hotkey Avatar answered Oct 24 '22 15:10

hotkey


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

like image 30
M.Sameer Avatar answered Oct 24 '22 16:10

M.Sameer