Kotlin String - toByteArray() Function



The Kotlin string toByteArray() function is used to return a byte array after the contents of the string have been encoded using the specified character set.

The default value of this function is UTF-8, It is commonly used in scenarios where string data need to be transmitted, stored, or processed in binary form.

Here are some use cases −

  • Network Communication: String are often converted to the byte array before transmitting data over a network.
  • File Writing: When we writing string data to a file in specific encoding.
  • Cryptography: When we prepare string data for encryption or hashing, a byte array is often required as input.
  • Interfacing with Java APIs: Some Java APIs, such as those working with ByteBuffers, often require input in the form of byte arrays.

Syntax

Following is the syntax of the Kotlin string toByteArray() function −

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

Parameters

This function accepts a charset, which specifies the character encoding. The default value is UTF_8, which is commonly used in modern applications.

Return value

This function returns a ByteArray.

Example 1: Convert a String to ByteArray

Following is the basic example of converting a string to a byte array using the toByteArray() function −

fun main() {
   val str = "Hello, TPians"
   val byteArray = str.toByteArray(Charsets.UTF_8)
   println("Following is the byte array:")
   println(byteArray.joinToString())
}

Output

Following is the output −

Following is the byte array:
72, 101, 108, 108, 111, 44, 32, 84, 80, 105, 97, 110, 115

Example 2: Computing & Formatting Hashes in Hexadecimal

In this example, we computes the "SHA-256 hash" of a given input string and formats the resulting hash as a human-readable hexadecimal string −

import java.security.MessageDigest

fun hashString(input: String): String {
   val digest = MessageDigest.getInstance("SHA-256")
   // Hashing the byte array
   val hashBytes = digest.digest(input.toByteArray(Charsets.UTF_8))
   // Convert the hash bytes to a hex string
   return hashBytes.joinToString("") { "%02x".format(it) }
}
fun main() {
   val string = "tutorialspoint"
   println(hashString(string))
}

Output

The following output prints the SHA-256 hash of the string "tutorialspoint" in hex format −

15e6e9ddbe43d9fe5745a1348bf1535b0456956d18473f5a3d14d6ab06737770

Example 3: Encode Using Charset (ISO-8859-1)

In this example, we convert the string to a ByteArray using the charset: "ISO-8859-1" encoding −

import java.security.MessageDigest

fun main() {
   val message = "Hello, World!"
   val byteArray = message.toByteArray(Charsets.ISO_8859_1)

   // Display the ByteArray
   println("ByteArray with ISO-8859-1: ${byteArray.joinToString()}")

   println("Characters from ByteArray with ISO-8859-1:")
   for (byte in byteArray) {
      print("${byte.toInt().toChar()} ")
   }
}

Output

Following is the output −

ByteArray with ISO-8859-1: 72, 101, 108, 108, 111, 44, 32, 87, 111, 114, 108, 100, 33
Characters from ByteArray with ISO-8859-1:
H e l l o ,   W o r l d !
kotlin_strings.htm
Advertisements