Conversion between Char and Int in Kotlin
This article explores different ways to convert between char and int in Kotlin.
1. Char to Int
A simple solution to get the value of a character as an Int is with the toInt() function.
|
1 2 3 4 5 |
fun main() { val c = 'A' val i = c.toInt() println(i) // 90 } |
To convert a complete string to a sequence of bytes, use the getBytes() function, which returns a byte array.
|
1 2 3 4 5 6 |
fun main() { val str = "ABC" val byteArray = str.toByteArray() println(byteArray.contentToString()) // [65, 66, 67] } |
To get the numeric value represented by the character in the specified radix, use the Character.digit() function.
|
1 2 3 4 5 |
fun main() { val c = '1' val i = Character.digit(c, 10) println(i) // 1 } |
2. Int to Char
To convert an Int value to a Char, use the toChar() function. The Int value should be in the range of Char codes Char.MIN_VALUE..Char.MAX_VALUE.
|
1 2 3 4 5 |
fun main() { val digit = 65 val c = digit.toChar() println(c) // 'a' } |
To get the corresponding character representation of the specified “digit” in the specified radix, use the Character.forDigit() function.
|
1 2 3 4 5 |
fun main() { val digit = 1 val c = Character.forDigit(digit, 10) println(c) // 1 } |
To convert the specified character (Unicode code point) to its UTF-16 representation, use the Character.toChars() function, which returns a char array.
|
1 2 3 4 5 |
fun main() { val digit = 65 val c = Character.toChars(digit) println(c) // A } |
That’s all about converting between char and int in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)