Convert a byte array to a string in Kotlin
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.
|
1 2 3 4 5 6 7 |
fun main() { val bytes = byteArrayOf(75, 111, 116, 108, 105, 110) val string = String(bytes) println(string) // Kotlin } |
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.
|
1 2 3 4 5 6 7 8 |
fun main() { // the byte array is encoded with UTF-16 val bytes = byteArrayOf(-2, -1, 0, 75, 0, 111, 0, 116, 0, 108, 0, 105, 0, 110) val string = String(bytes, Charsets.UTF_16) println(string) // Kotlin } |
That’s all about converting a byte array to string 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 :)