In this tutorial, you shall learn how to convert a given string to a byte array in Kotlin, using String.toByteArray() method, with examples.

Kotlin – Convert String to Byte Array

To convert a string to byte array in Kotlin, use String.toByteArray() method. String.toByteArray() method returns a Byte Array created using the characters of the calling string.

Syntax

The syntax to call toByteArray() method on String str is

</>
Copy
str.toByteArray()

Examples

1. Convert given string “apple” to byte array

In the following example, we take a string and convert this to an array of bytes using String.toByteArray() method.

Main.kt

</>
Copy
fun main() {
    val str = "apple"
    val bytes = str.toByteArray()
    for (byte in bytes) println(byte)
}

Output

97
112
112
108
101

Conclusion

In this Kotlin Tutorial, we learned how to convert a String to Byte Array using String.toByteArray() method, with examples.