This article explores different ways to convert a byte array to a string in Kotlin.

We should best avoid the conversion between byte array and string since a Kotlin String is used to store the textual data, whereas a byte array stores the binary data. However, if you still need it, you can convert a byte array to string in Kotlin using the following methods:

1. ASCII character set

You can directly pass the byte array to the String constructor, which converts the data from the specified array of bytes to characters. You can specify the default UTF-8 character encoding or skip it for the ASCII character set.

Download Code

2. Non-ASCII character set

The above solution works fine for the ASCII character set. For non-ASCII character sets, you should explicitly specify the original encoding used while converting to bytes sequences.

Consider the following program, where the byte array is encoded with UTF-16. To decode the byte array, the UTF-16 character set is specified to the String constructor.

Download Code

That’s all about converting a byte array to string in Kotlin.