Added byte array extension to print

master Version_2.0
Robinson 2023-08-21 00:54:22 +02:00
parent d48c321868
commit 805f412122
No known key found for this signature in database
GPG Key ID: 8E7DB78588BD6F5C
1 changed files with 92 additions and 0 deletions

View File

@ -15,6 +15,8 @@
*/
package dorkbox.bytes
import java.util.ArrayList
object ArrayExtensions {
/**
* Gets the version number.
@ -127,3 +129,93 @@ fun ByteArray.xor(keyArray: ByteArray) {
this[i] = (this[i].toInt() xor keyArray[keyIndex++ % keyLength].toInt()).toByte()
}
}
private val LINE_SEPARATOR = System.getProperty("line.separator", "\n")
fun ByteArray.printRaw(lineLength: Int = 0): String {
return if (lineLength > 0) {
val length = this.size
val comma = length - 1
val builder = StringBuilder(length + length / lineLength)
for (i in 0 until length) {
builder.append(this[i].toInt())
if (i < comma) {
builder.append(",")
}
if (i > 0 && i % lineLength == 0) {
builder.append(LINE_SEPARATOR)
}
}
builder.toString()
} else {
val length = this.size
val comma = length - 1
val builder = StringBuilder(length + length)
for (i in 0 until length) {
builder.append(this[i].toInt())
if (i < comma) {
builder.append(",")
}
}
builder.toString()
}
}
fun ByteArray.print(length: Int = this.size, includeByteCount: Boolean = true): String {
return this.print(0, length, includeByteCount, 40, null)
}
fun ByteArray.print(
inputOffset: Int,
length: Int,
includeByteCount: Boolean,
lineLength: Int = 40,
header: String? = null
): String {
val comma = length - 1
var builderLength = length + comma + 2
if (includeByteCount) {
builderLength += 7 + length.toString().length
}
if (lineLength > 0) {
builderLength += length / lineLength
}
if (header != null) {
builderLength += header.length + 2
}
val builder = StringBuilder(builderLength)
if (header != null) {
builder.append(header).append(LINE_SEPARATOR)
}
if (includeByteCount) {
builder.append("Bytes: ").append(length).append(LINE_SEPARATOR)
}
builder.append("{")
for (i in inputOffset until length) {
builder.append(this[i].toInt())
if (i < comma) {
builder.append(",")
}
if (i > inputOffset && lineLength > 0 && i % lineLength == 0) {
builder.append(LINE_SEPARATOR)
}
}
builder.append("}")
return builder.toString()
}