hexToByteArray

Parses a byte array from this string using the specified format.

The string must conform to the structure defined by the format. Note that only the HexFormat.bytes property of the format instance affects the parsing of a byte array.

Parsing is performed in a case-insensitive manner for both the hexadecimal digits and the elements (prefix, suffix, separators) defined in the HexFormat.bytes property. Additionally, any of the char sequences CRLF, LF and CR is considered a valid line separator.

Refer to HexFormat.BytesHexFormat for details about the available format options and their impact on parsing.

Since Kotlin

1.9

Return

the byte array parsed from this string.

Parameters

format

the HexFormat to use for parsing, HexFormat.Default by default.

Throws

if this string does not conform to the specified format.

Samples

import kotlin.test.*

fun main() { 
   //sampleStart 
   val expectedData = byteArrayOf(0xDE.toByte(), 0x2D, 0x02, 0xC0.toByte(), 0x5C, 0x0E)

// Using the default format
println("de2d02c05c0e".hexToByteArray().contentEquals(expectedData)) // true

// Parsing is case-insensitive
println("DE2D02C05C0E".hexToByteArray().contentEquals(expectedData)) // true

// Using a custom format
val format = HexFormat {
    bytes {
        bytesPerLine = 4
        byteSeparator = " " // One space
        bytePrefix = "0x"
    }
}
println("0xDE 0x2D 0x02 0xC0\n0x5C 0x0E".hexToByteArray(format).contentEquals(expectedData)) // true

// Parsing unsigned bytes results in the unsigned versions of the same bytes
val expectedUnsignedData = expectedData.toUByteArray()
println("de2d02c05c0e".hexToUByteArray().contentEquals(expectedUnsignedData)) // true

// Parsing fails if the input string does not conform to the specified format.
// In this case, there is no line separator after the fourth formatted byte.
// "0xDE 0x2D 0x02 0xC0 0x5C 0x0E".hexToByteArray(format) // will fail with IllegalArgumentException 
   //sampleEnd
}