Converting Kotlin Strings to Integers

Introduces how to convert strings to integers and integers to strings.

Converting from String to Int

Kotlin defines the toIntOrNull() extension function on the String class, and it can convert an arbitrary string to the numeric type Int. As the name suggests, it returns null when the string cannot be converted.

val num1 = "100".toIntOrNull()
val num2 = "xyz".toIntOrNull()

Output:

100
null

Because you can specify a radix as a parameter of String#toIntOrNull(), you can also parse strings written in binary or hexadecimal notation as shown below.

val num1 = "10000000".toIntOrNull(2)
val num2 = "FFFF".toIntOrNull(16)
val num3 = "0xFFFF".toIntOrNull(16)

Output:

128
65535
null

As you can see from the result above, note that toIntOrNull() returns null when a hexadecimal string includes the 0x prefix.

There is a similar function, String#toInt(), but when parsing fails it throws NumberFormatException instead of returning null. Use the appropriate function for your needs.

try {
    val num = "xyz".toInt()
    println(num)
} catch (ex : NumberFormatException) {
    System.err.println(ex)
}

Converting from Int to String

With Int.toString(radix), you can convert a number (Int) to a string representation in an arbitrary radix.

val num = 255
println(num.toString(2))
println(num.toString(8))
println(num.toString(16))

Output:

11111111
377
ff

It can be used similarly to the toBinaryString, toOctalString, and toHexString methods in Java’s Integer class, but be aware that the result differs when you pass a negative value.

val num = -255
println(num.toString(2))
println(num.toString(8))
println(num.toString(16))
println(Integer.toBinaryString(num))
println(Integer.toOctalString(num))
println(Integer.toHexString(num))

Output:

11111111
-377
-ff
11111111111111111111111100000001
37777777401
ffffff01