Files
bytes.kt/src/commonMain/kotlin/com/infendro/bytearray/UInt.kt

44 lines
969 B
Kotlin

package com.infendro.bytearray
import com.infendro.bytearray.ByteOrder.BIG_ENDIAN
fun UInt.toByteArray(
order: ByteOrder = BIG_ENDIAN,
): ByteArray {
val bytes = ByteArray(4) { i ->
val offset = (3 - i) * 8
(this shr offset).toByte()
}
return order.normalize(bytes)
}
fun UIntArray.toByteArray(
order: ByteOrder = BIG_ENDIAN,
): ByteArray {
val bytes = mutableListOf<Byte>()
for (n in this) {
bytes += n.toByteArray(order).toList()
}
return bytes.toByteArray()
}
fun UInt.toUByteArray(
order: ByteOrder = BIG_ENDIAN,
): UByteArray {
val bytes = UByteArray(4) { i ->
val offset = (3 - i) * 8
(this shr offset).toUByte()
}
return order.normalize(bytes)
}
fun UIntArray.toUByteArray(
order: ByteOrder = BIG_ENDIAN,
): UByteArray {
val bytes = mutableListOf<UByte>()
for (n in this) {
bytes += n.toUByteArray(order)
}
return bytes.toUByteArray()
}