3 different ways to convert a byte array to string in Kotlin

Kotlin convert a byte array to string:

This article will show you different ways to convert a byte array to an array in Kotlin. If you are receiving data in bytes and if you are sure that the data is of a string, you can use any of these methods to convert that array of bytes to string.

The byte array can be converted to string by using the Kotlin String constructor. We can also define the character encoding, by default it is UTF-8. Let’s learn how to do that with examples.

Example 1: Byte array to string with UTF-8 character encoding:

Let’s take a look at the below example:

fun main() {
    val byteArray = byteArrayOf(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 32, 33, 33)

    val str = String(byteArray)

    println(str)
}

Here,

  • byteArray is an array of bytes. It is UTF-8 encoded or ASCII characters.
  • We are passing the byte array to the String constructor. Since we are not specifying the character set, it will consider it as UTF-8.

If you run, it will print:

Hello World !!

Example 2: Byte array to string with different character encoding:

Let’s try a byte array encoded with a different character encoding.

fun main() {
    val byteArray = byteArrayOf(-2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 32, 0, 33, 0, 33)

    val str = String(byteArray, Charsets.UTF_16)

    println(str)
}

Here, byteArray is an array of bytes and encoded with UTF-16 character encoding. So, while passing the byte array, we have to pass Charsets.UTF_16 as the second parameter.

It will print the same result.

Hello World !!

Example 3: Byte array to string conversion by using toString:

The ByteArray provides a method called toString that can be used to convert an array of bytes to a string. It is defined as like below:

public inline fun ByteArray.toString(charset: Charset): String

The character set parameter is the character encoding value.

Let’s try this method both UTF-8 and UTF-16 byte arrays:

fun main() {
    val byteArrayUtf8 = byteArrayOf(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 32, 33, 33)
    val byteArrayUtf16 = byteArrayOf(-2, -1, 0, 72, 0, 101, 0, 108, 0, 108, 0, 111, 0, 32, 0, 87, 0, 111, 0, 114, 0, 108, 0, 100, 0, 32, 0, 33, 0, 33)

    val strUtf8 = byteArrayUtf8.toString(Charsets.UTF_8)
    val strUtf16 = byteArrayUtf16.toString(Charsets.UTF_16)

    println(strUtf8)
    println(strUtf16)
}

It will print: Kotlin convert byte array to string example

You might also like: