This commit is contained in:
49
src/commonMain/kotlin/com/infendro/bytearray/UInt.kt
Normal file
49
src/commonMain/kotlin/com/infendro/bytearray/UInt.kt
Normal file
@@ -0,0 +1,49 @@
|
||||
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 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 Collection<Byte>.toUInt(
|
||||
order: ByteOrder = BIG_ENDIAN,
|
||||
): UInt {
|
||||
return toByteArray()
|
||||
.toUInt(order)
|
||||
}
|
||||
|
||||
fun ByteArray.toUIntArray(
|
||||
order: ByteOrder = BIG_ENDIAN,
|
||||
): UIntArray {
|
||||
if (size % 4 != 0) throw Exception()
|
||||
|
||||
return toList()
|
||||
.chunked(4)
|
||||
.map { it.toUInt(order) }
|
||||
.toUIntArray()
|
||||
}
|
||||
|
||||
fun Collection<Byte>.toUIntArray(
|
||||
order: ByteOrder = BIG_ENDIAN,
|
||||
): UIntArray {
|
||||
return toByteArray()
|
||||
.toUIntArray(order)
|
||||
}
|
||||
Reference in New Issue
Block a user