Skip to main content

How to convert a string to a hexadecimal representation in Kotlin

How to convert a string to a hexadecimal representation in Kotlin.

Here's a step-by-step tutorial on how to convert a string to a hexadecimal representation in Kotlin:

Step 1: Declare the input string

To begin, declare the string that you want to convert to a hexadecimal representation. For example, let's say we have the following string:

val inputString = "Hello World"

Step 2: Convert the string to a byte array

Next, convert the input string to a byte array. This is necessary because hexadecimal representation is commonly used to represent binary data, and each character in a string can be represented by one or more bytes. To convert the string to a byte array, you can use the toByteArray() function:

val byteArray = inputString.toByteArray()

Step 3: Convert each byte to a hexadecimal string

Now, iterate over each byte in the byte array and convert it to its hexadecimal representation. In Kotlin, you can use the format() function with the %02X format specifier to achieve this. The %02X specifier formats the byte as a two-digit hexadecimal number with leading zeros if necessary:

val hexStringBuilder = StringBuilder()
for (byte in byteArray) {
val hexString = "%02X".format(byte)
hexStringBuilder.append(hexString)
}
val hexString = hexStringBuilder.toString()

Step 4: Print or use the hexadecimal representation

Finally, you can either print or use the resulting hexadecimal representation as needed. In this example, let's print the hexadecimal representation of the input string:

println(hexString)

Putting it all together, here's the complete example:

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

val hexStringBuilder = StringBuilder()
for (byte in byteArray) {
val hexString = "%02X".format(byte)
hexStringBuilder.append(hexString)
}
val hexString = hexStringBuilder.toString()

println(hexString)
}

When you run this code, it will output the hexadecimal representation of the input string "Hello World":

48656C6C6F20576F726C64

That's it! You have successfully converted a string to its hexadecimal representation in Kotlin.