Convert char to its ASCII code in Kotlin
This article explores different ways to convert a char to its ASCII code in Kotlin.
A simple solution to convert a char to its ASCII code is using the toInt() function, which returns the value of the character as an Int. Here’s a Kotlin program demonstrating its usage:
|
1 2 3 4 5 |
fun main() { val c = 'x' val ascii = c.toInt() println(ascii) // 120 } |
Alternatively, we can get the value of this character as a Byte and convert this Byte value to Int:
|
1 2 3 4 5 |
fun main() { val c = 'b' val ascii = c.toByte().toInt() println(ascii) // 98 } |
To convert each character of a string to its ASCII code, we can encode the string into a sequence of bytes using the getBytes() function, resulting in a new byte array. The following code example shows invocation for this method:
|
1 2 3 4 5 6 |
fun main() { val s = "Kotlin" val bytes = s.toByteArray() println(bytes.contentToString()) // [75, 111, 116, 108, 105, 110] } |
That’s all about converting char to its ASCII code 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 :)