This article explores different ways to convert between String and Byte Array in Kotlin.

1. String to Byte Array

The toByteArray() function encodes the string into a sequence of bytes using the platform’s default charset. A typical invocation for this method would look like:

Download Code

 
You can specify the character encoding to the toByteArray() function, as shown below:

Download Code

Output:

[-2, -1, 0, 75, 0, 111, 0, 116, 0, 108, 0, 105, 0, 110]

 
Alternatively, use the toByteArray() function to encode a string to an array of bytes.

Download Code

2. Byte Array to String

To get the string back from a byte array, pass the byte array to the String constructor with the charset used for encoding, as shown below:

Download Code

 
The String constructor optionally takes the charset used for encoding. For instance, the following program converts the specified array of bytes to characters using the Charsets.UTF_16 encoding.

Download Code

That’s all about conversion between String and Byte Array in Kotlin.