How to convert a string to byte array in Kotlin

How to convert a string to byte array in Kotlin:

In this post, we will learn how to convert a string to a byte array in Kotlin. The String class provides a method called toByteArray in Kotlin that we can use to convert a string to a byte array. We will learn the syntax of this method and how to use it to convert a string to byte array.

Syntax of toByteArray:

The toByteArray method is defined as like below:

fun str.toByteArray(charset: Charset = Charsets.UTF_8): ByteArray

This method can be called on any string variable. It takes one optional parameter. This is the character set to use for the string-byte array conversion. By default, it is UTF-8.

It returns a ByteArray.

Example of toByteArray:

Let’s try the toByteArray method with an example:

fun main() {
    val givenString = "Hello World !!"
    val byteArray = givenString.toByteArray()

    println("Byte Array: ${byteArray.contentToString()}")
}

Here, we are converting the string givenString to a byte array. The contentToString() method returns a string representation of the byte array.

If you run this program, it will print:

Byte Array: [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 32, 33, 33]

We can also convert the byte array to a string to check if the conversion is correct.

fun main() {
    val givenString = "Hello World !!"
    val byteArray = givenString.toByteArray()

    println("Byte Array: ${byteArray.contentToString()}")
    println("Original String: ${byteArray.toString(Charsets.UTF_8)}")
}

The second print statement will print the original string. We are passing Charsets.UTF_8 to the toString() method as this is the default Charsets used with toByteArray.

Example to use toByteArray with different Charsets:

Let’s try toByteArray with a different Charsets:

fun main() {
    val givenString = "Hello World !!"
    val byteArray = givenString.toByteArray(Charsets.US_ASCII)

    println("Byte Array: ${byteArray.contentToString()}")
    println("Original String: ${byteArray.toString(Charsets.US_ASCII)}")
}

It uses US_ASCII. The program will print the same output as we are printing the string representation of the byte array. The byte array data will be different.

Kotlin convert string to byte array

You might also like: