bytesPerLine

Common
JVM
JS
Native
1.0
val bytesPerLine: Int
(source)

The maximum number of bytes per line, Int.MAX_VALUE by default.

When formatting, bytes are split into lines with bytesPerLine bytes in each line, except for the last line, which may have fewer bytes if the total number of bytes does not divide evenly by this value. Adjacent lines are separated by the line feed (LF) character '\n'. Note that if this value is greater than or equal to the size of the byte array, the entire array will be formatted as a single line without any line breaks.

When parsing, the input string must be split into lines accordingly, with bytesPerLine bytes in each line, except for the last line, which may have fewer bytes. Any of the char sequences CRLF, LF, or CR is considered a valid line separator.

import kotlin.test.*

fun main(args: Array<String>) {
//sampleStart
val data = ByteArray(7) { it.toByte() }

// By default, bytesPerLine is set to Int.MAX_VALUE, which exceeds data.size.
// Therefore, all bytes are formatted as a single line without any line breaks.
println(data.toHexString()) // 00010203040506
println("\"00010203040506\".hexToByteArray().contentEquals(data) is ${"00010203040506".hexToByteArray().contentEquals(data)}") // true

// Setting bytesPerLine to 3 splits the output into 3 lines with 3, 3, and 1 bytes, respectively.
// Each line is separated by a line feed (LF) character.
val threePerLineFormat = HexFormat {
    bytes.bytesPerLine = 3
}
println(data.toHexString(threePerLineFormat)) // 000102\n030405\n06

// When parsing, any of the line separators CRLF, LF, and CR are accepted.
println("\"000102\\n030405\\r\\n06\".hexToByteArray(threePerLineFormat).contentEquals(data) is ${"000102\n030405\r\n06".hexToByteArray(threePerLineFormat).contentEquals(data)}") // true

// Parsing fails if the input string does not conform to specified format.
// In this case, lines do not consist of the expected number of bytes.
// "0001\n0203\n0405\n06".hexToByteArray(threePerLineFormat) // will fail with IllegalArgumentException
//sampleEnd
}