Files
bytes.kt/src/commonMain/kotlin/com/infendro/bytearray/Long.kt
Infendro ded3b31aa4
All checks were successful
/ publish (push) Successful in 2m39s
initial commit
2025-07-24 20:24:17 +02:00

50 lines
1.0 KiB
Kotlin

package com.infendro.bytearray
import com.infendro.bytearray.ByteOrder.BIG_ENDIAN
fun Long.toByteArray(
order: ByteOrder = BIG_ENDIAN,
): ByteArray {
val bytes = ByteArray(8) { i ->
val offset = (7 - i) * 8
(this ushr offset).toByte()
}
return order.normalize(bytes)
}
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 Collection<Byte>.toLong(
order: ByteOrder = BIG_ENDIAN,
): Long {
return toByteArray()
.toLong(order)
}
fun ByteArray.toLongArray(
order: ByteOrder = BIG_ENDIAN,
): LongArray {
if (size % 8 != 0) throw Exception()
return toList()
.chunked(8)
.map { it.toLong(order) }
.toLongArray()
}
fun Collection<Byte>.toLongArray(
order: ByteOrder = BIG_ENDIAN,
): LongArray {
return toByteArray()
.toLongArray(order)
}