bytesPerGroup
Defines BytesHexFormat.bytesPerGroup of the format being built, Int.MAX_VALUE by default.
The value must be positive.
Refer to BytesHexFormat.bytesPerGroup for details about how this format option affects the formatting and parsing results.
Since Kotlin
1.9Throws
if a non-positive value is assigned to this property.
Samples
import kotlin.test.*
fun main() {
//sampleStart
val data = ByteArray(7) { it.toByte() }
// By default, both bytesPerLine and bytesPerGroup are set to Int.MAX_VALUE, which exceeds data.size.
// Hence, all bytes are formatted as a single line and a single group.
println(data.toHexString()) // 00010203040506
println("\"00010203040506\".hexToByteArray().contentEquals(data) is ${"00010203040506".hexToByteArray().contentEquals(data)}") // true
// Setting bytesPerGroup to 2 with the default group separator, which is two spaces.
val twoPerGroupFormat = HexFormat {
bytes.bytesPerGroup = 2
}
println(data.toHexString(twoPerGroupFormat)) // 0001 0203 0405 06
println("\"0001 0203 0405 06\".hexToByteArray(twoPerGroupFormat).contentEquals(data) is ${"0001 0203 0405 06".hexToByteArray(twoPerGroupFormat).contentEquals(data)}") // true
// Specifying a custom group separator, a dot in this case.
val dotGroupSeparatorFormat = HexFormat {
bytes {
bytesPerGroup = 2
groupSeparator = "."
}
}
println(data.toHexString(dotGroupSeparatorFormat)) // 0001.0203.0405.06
println("\"0001.0203.0405.06\".hexToByteArray(dotGroupSeparatorFormat).contentEquals(data) is ${"0001.0203.0405.06".hexToByteArray(dotGroupSeparatorFormat).contentEquals(data)}") // true
// If bytesPerLine is less than or equal to bytesPerGroup, each line is treated as a single group,
// hence no group separator is used.
val lessBytesPerLineFormat = HexFormat {
bytes {
bytesPerLine = 3
bytesPerGroup = 4
groupSeparator = "|"
}
}
println(data.toHexString(lessBytesPerLineFormat)) // 000102\n030405\n06
println("\"000102\\n030405\\n06\".hexToByteArray(lessBytesPerLineFormat).contentEquals(data) is ${"000102\n030405\n06".hexToByteArray(lessBytesPerLineFormat).contentEquals(data)}") // true
// When bytesPerLine is greater than bytesPerGroup, each line is split into multiple groups.
val moreBytesPerLineFormat = HexFormat {
bytes {
bytesPerLine = 5
bytesPerGroup = 2
groupSeparator = "."
}
}
println(data.toHexString(moreBytesPerLineFormat)) // 0001.0203.04\n0506
println("\"0001.0203.04\\n0506\".hexToByteArray(moreBytesPerLineFormat).contentEquals(data) is ${"0001.0203.04\n0506".hexToByteArray(moreBytesPerLineFormat).contentEquals(data)}") // true
// Parsing fails due to incorrect group separator.
// "0001 0203 04\n0506".hexToByteArray(moreBytesPerLineFormat) // will fail with IllegalArgumentException
//sampleEnd
}