Programa Kotlin para converter array de bytes em hexadecimal

Neste programa, você aprenderá diferentes técnicas para converter a matriz de bytes em hexadecimal no Kotlin.

Exemplo 1: converter matriz de bytes em valor hexadecimal

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

Quando você executa o programa, a saída será:

 0A020F0B

No programa acima, temos uma matriz de bytes chamada bytes. Para converter a matriz de bytes em valor hexadecimal, percorremos cada byte na matriz e usamos String's format().

Usamos %02Xpara imprimir duas casas ( 02) do Xvalor Hexadecimal ( ) e armazená-lo na string st.

Este é um processo relativamente mais lento para a conversão de grandes matrizes de bytes. Podemos aumentar drasticamente a velocidade de execução usando as operações de byte mostradas abaixo.

Exemplo 2: converter matriz de bytes em valor hexadecimal usando operações de bytes

 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) ( val bytes = byteArrayOf(10, 2, 15, 11) val s = bytesToHex(bytes) println(s) )

A saída do programa é a mesma do Exemplo 1.

Aqui está o código Java equivalente: programa Java para converter array de bytes em hexadecimal.

Artigos interessantes...