This commit is contained in:
49
src/commonMain/kotlin/com/infendro/bytearray/ULong.kt
Normal file
49
src/commonMain/kotlin/com/infendro/bytearray/ULong.kt
Normal file
@@ -0,0 +1,49 @@
|
||||
package com.infendro.bytearray
|
||||
|
||||
import com.infendro.bytearray.ByteOrder.BIG_ENDIAN
|
||||
|
||||
fun ULong.toByteArray(
|
||||
order: ByteOrder = BIG_ENDIAN,
|
||||
): ByteArray {
|
||||
val bytes = ByteArray(8) { i ->
|
||||
val offset = (7 - i) * 8
|
||||
(this shr offset).toByte()
|
||||
}
|
||||
return order.normalize(bytes)
|
||||
}
|
||||
|
||||
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 Collection<Byte>.toULong(
|
||||
order: ByteOrder = BIG_ENDIAN,
|
||||
): ULong {
|
||||
return toByteArray()
|
||||
.toULong(order)
|
||||
}
|
||||
|
||||
fun ByteArray.toULongArray(
|
||||
order: ByteOrder = BIG_ENDIAN,
|
||||
): ULongArray {
|
||||
if (size % 8 != 0) throw Exception()
|
||||
|
||||
return toList()
|
||||
.chunked(8)
|
||||
.map { it.toULong(order) }
|
||||
.toULongArray()
|
||||
}
|
||||
|
||||
fun Collection<Byte>.toULongArray(
|
||||
order: ByteOrder = BIG_ENDIAN,
|
||||
): ULongArray {
|
||||
return toByteArray()
|
||||
.toULongArray(order)
|
||||
}
|
||||
Reference in New Issue
Block a user