Conversion between String and Byte Array in Kotlin
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:
|
1 2 3 4 5 |
fun main() { val s = "Kotlin" val byteArray = s.toByteArray() println(byteArray.contentToString()) // [75, 111, 116, 108, 105, 110] } |
You can specify the character encoding to the toByteArray() function, as shown below:
|
1 2 3 4 5 |
fun main() { val s = "Kotlin" val byteArray = s.toByteArray(Charsets.UTF_16) println(byteArray.contentToString()) } |
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.
|
1 2 3 4 5 |
fun main() { val s = "Kotlin" val byteArray = s.encodeToByteArray() println(byteArray.contentToString()) // [75, 111, 116, 108, 105, 110] } |
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:
|
1 2 3 4 5 6 |
fun main() { val byteArray = byteArrayOf(75, 111, 116, 108, 105, 110) val s = String(byteArray) println(s) // Kotlin } |
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.
|
1 2 3 4 5 6 |
fun main() { val byteArray = byteArrayOf(-2, -1, 0, 75, 0, 111, 0, 116, 0, 108, 0, 105, 0, 110) val s = String(byteArray, Charsets.UTF_16) println(s) // Kotlin } |
That’s all about conversion between String and Byte Array 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 :)