Files
bytes.kt/src/commonMain/kotlin/com/infendro/bytearray/ByteArray.kt
2025-11-10 15:52:24 +01:00

149 lines
3.0 KiB
Kotlin

package com.infendro.bytearray
import com.infendro.bytearray.ByteOrder.BIG_ENDIAN
import kotlin.experimental.and
import kotlin.experimental.or
import kotlin.experimental.xor
infix fun ByteArray.and(
that: ByteArray,
): ByteArray {
if (this.size != that.size) throw Exception()
return ByteArray(size) { i ->
this[i] and that[i]
}
}
infix fun ByteArray.or(
that: ByteArray,
): ByteArray {
if (this.size != that.size) throw Exception()
return ByteArray(size) { i ->
this[i] or that[i]
}
}
infix fun ByteArray.xor(
that: ByteArray,
): ByteArray {
if (this.size != that.size) throw Exception()
return ByteArray(size) { i ->
this[i] xor that[i]
}
}
fun ByteArray.padStart(
length: Int,
padByte: Byte,
): ByteArray {
return buildList {
repeat(length - size) {
add(padByte)
}
addAll(this)
}.toByteArray()
}
fun ByteArray.padEnd(
length: Int,
padByte: Byte,
): ByteArray {
return buildList {
addAll(this)
repeat(length - size) {
add(padByte)
}
}.toByteArray()
}
fun ByteArray.toInt(
order: ByteOrder = BIG_ENDIAN,
): Int {
if (size != 4) throw Exception()
val bytes = order.normalize(this)
return bytes.fold(0) { acc, byte ->
(acc shl 8) or (byte.toInt() and 0xFF)
}
}
fun ByteArray.toIntArray(
order: ByteOrder = BIG_ENDIAN,
): IntArray {
if (size % 4 != 0) throw Exception()
return toList()
.chunked(4)
.map { it.toByteArray().toInt(order) }
.toIntArray()
}
fun ByteArray.toLong(
order: ByteOrder = BIG_ENDIAN,
): Long {
if (size != 8) throw Exception()
val bytes = order.normalize(this)
return bytes.fold(0L) { acc, byte ->
(acc shl 8) or (byte.toLong() and 0xFFL)
}
}
fun ByteArray.toLongArray(
order: ByteOrder = BIG_ENDIAN,
): LongArray {
if (size % 8 != 0) throw Exception()
return toList()
.chunked(8)
.map { it.toByteArray().toLong(order) }
.toLongArray()
}
fun ByteArray.toUInt(
order: ByteOrder = BIG_ENDIAN,
): UInt {
if (size != 4) throw Exception()
val bytes = order.normalize(this)
return bytes.fold(0U) { acc, byte ->
(acc shl 8) or (byte.toUInt() and 0xFFU)
}
}
fun ByteArray.toUIntArray(
order: ByteOrder = BIG_ENDIAN,
): UIntArray {
if (size % 4 != 0) throw Exception()
return toList()
.chunked(4)
.map { it.toByteArray().toUInt(order) }
.toUIntArray()
}
fun ByteArray.toULong(
order: ByteOrder = BIG_ENDIAN,
): ULong {
if (size != 8) throw Exception()
val bytes = order.normalize(this)
return bytes.fold(0UL) { acc, byte ->
(acc shl 8) or (byte.toULong() and 0xFFUL)
}
}
fun ByteArray.toULongArray(
order: ByteOrder = BIG_ENDIAN,
): ULongArray {
if (size % 8 != 0) throw Exception()
return toList()
.chunked(8)
.map { it.toByteArray().toULong(order) }
.toULongArray()
}