English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Kotlin program converts byte array to hexadecimal

Comprehensive Collection of Kotlin Examples

In this program, you will learn different methods to convert a byte array to hexadecimal in Kotlin.

Example1:Convert byte array to hexadecimal value

fun main(args: Array<String>) {
    val bytes = byteArrayOf(10, 2, 15, 11)
    for (b in bytes) {
        val st = String.format("%02X", b)
        print(st)
    }
}

When running the program, the output is:

0A020F0B

In the above program, we have an array named bytes. To convert the byte array to a hexadecimal value, we iterate over each byte in the array and use String's format().

We use%02X prints two positions (02) hexadecimal (X) value and store it in the string st.

For large byte array conversion, this is a relatively slow process. We can use the byte operations shown below to greatly improve execution speed.

Example2:Convert byte array to hexadecimal value using byte operations

import kotlin.experimental.and
private val hexArray = "0123456789ABCDEF".toCharArray()
fun bytesToHex(bytes: ByteArray): String {
    val hexChars = CharArray(bytes.size * 2)
    for (j in bytes.indices) {
        val v = (bytes[j] and 0xFF.toByte()).toInt()
        hexChars[j * 2] = hexArray[v ushr} 4]
        hexChars[j * 2 + 1] = hexArray[v and 0x0F]
    }
    return String(hexChars)
}
fun main(args: Array<String>) {
    val bytes = byteArrayOf(10, 2, 15, 11)
    val s = bytesToHex(bytes)
    println(s)
}

The output of this program is the same as the example1Same.

This is the equivalent Java code:Java Program to Convert Byte Array to Hexadecimal.

Comprehensive Collection of Kotlin Examples