bytePrefix
The string that immediately precedes the two-digit hexadecimal representation of each byte.
When formatting, this string is used as a prefix for the hexadecimal representation of each byte.
When parsing, the hexadecimal representation of each byte must be prefixed by this string. The parsing of this prefix is performed in a case-insensitive manner.
Since Kotlin
1.9Samples
import kotlin.test.*
fun main() {
//sampleStart
val data = ByteArray(4) { it.toByte() }
// By default, the bytePrefix is an empty string, so bytes are formatted without any prefix.
println(data.toHexString()) // 00010203
println("\"00010203\".hexToByteArray().contentEquals(data) is ${"00010203".hexToByteArray().contentEquals(data)}") // true
// Specifying a custom byte prefix, "0x" in this case, to precede each byte.
// A space is used as a byte separator for clarity in the output.
val bytePrefixFormat = HexFormat {
bytes.bytePrefix = "0x"
bytes.byteSeparator = " "
}
println(data.toHexString(bytePrefixFormat)) // 0x00 0x01 0x02 0x03
println("\"0x00 0x01 0x02 0x03\".hexToByteArray(bytePrefixFormat).contentEquals(data) is ${"0x00 0x01 0x02 0x03".hexToByteArray(bytePrefixFormat).contentEquals(data)}") // true
// Parsing fails due to incorrect byte prefix.
// In this case, the input string is lacking the necessary byte prefixes.
// "00 01 02 03".hexToByteArray(bytePrefixFormat) // will fail with IllegalArgumentException
//sampleEnd
}