Skip to content

Commit 5348f97

Browse files
[KTLN-872] Convert hex string to byte array in Kotlin (#968)
* added unit tests * made code fixes
1 parent d8e4362 commit 5348f97

File tree

1 file changed

+60
-0
lines changed
  • core-kotlin-modules/core-kotlin-strings-5/src/test/kotlin/com/baeldung/hexToByte

1 file changed

+60
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package com.baeldung.hexToByte
2+
3+
import org.junit.jupiter.api.Assertions.assertArrayEquals
4+
import org.junit.jupiter.api.Test
5+
import java.math.BigInteger
6+
7+
class HexToByteUnitTest {
8+
9+
@Test
10+
fun `convert hex string to byte array using for loop`() {
11+
val hexString = "48656C6C6F20576F726C64"
12+
val expectedByteArray = byteArrayOf(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)
13+
assertArrayEquals(expectedByteArray, hexStringToByteArrayUsingForLoop(hexString))
14+
}
15+
16+
@Test
17+
fun `convert hex string to byte array using BigInteger`() {
18+
val hexString = "48656C6C6F20576F726C64"
19+
val expectedByteArray = byteArrayOf(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)
20+
21+
assertArrayEquals(expectedByteArray, hexStringToByteArrayUsingBigInteger(hexString))
22+
}
23+
24+
@Test
25+
fun `convert hex string to byte array using BigInteger using standard libraries methods`() {
26+
val hexString = "48656C6C6F20576F726C64"
27+
val expectedByteArray = byteArrayOf(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)
28+
29+
assertArrayEquals(expectedByteArray, hexStringToByteArrayUsingStandardLibraryMethods(hexString))
30+
}
31+
32+
@OptIn(ExperimentalStdlibApi::class)
33+
@Test
34+
fun `convert hex string to byte array using hexToByteArray`() {
35+
val hexString = "48656C6C6F20576F726C64"
36+
val expectedByteArray = byteArrayOf(72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100)
37+
38+
assertArrayEquals(expectedByteArray, hexString.hexToByteArray())
39+
}
40+
}
41+
fun hexStringToByteArrayUsingForLoop(hex: String): ByteArray {
42+
val length = hex.length
43+
val byteArray = ByteArray(length / 2)
44+
for (i in byteArray.indices) {
45+
val index = i * 2
46+
val byte = hex.substring(index, index + 2).toInt(16).toByte()
47+
byteArray[i] = byte
48+
}
49+
return byteArray
50+
}
51+
fun hexStringToByteArrayUsingBigInteger(hexString: String): ByteArray {
52+
val bigInteger = BigInteger(hexString, 16)
53+
return bigInteger.toByteArray()
54+
}
55+
56+
fun hexStringToByteArrayUsingStandardLibraryMethods(hex: String): ByteArray {
57+
return hex.chunked(2)
58+
.map { it.toInt(16).toByte() }
59+
.toByteArray()
60+
}

0 commit comments

Comments
 (0)