Files
bytes.kt/src/commonMain/kotlin/com/infendro/bytes/ubytearray/Conversion.kt
2026-01-14 15:36:50 +01:00

58 lines
2.5 KiB
Kotlin

package com.infendro.bytes.ubytearray
import com.infendro.bytes.ByteOrder
import com.infendro.bytes.ByteOrder.BIG_ENDIAN
import com.infendro.bytes.ByteOrder.LITTLE_ENDIAN
fun UByteArray.toUInt(startIndex: Int = 0, order: ByteOrder = BIG_ENDIAN): UInt {
require(startIndex in 0..(size - 4))
return when (order) {
BIG_ENDIAN -> {
(this[startIndex].toUInt() shl 24) or (this[startIndex + 1].toUInt() shl 16) or
(this[startIndex + 2].toUInt() shl 8) or this[startIndex + 3].toUInt()
}
LITTLE_ENDIAN -> {
this[startIndex].toUInt() or (this[startIndex + 1].toUInt() shl 8) or
(this[startIndex + 2].toUInt() shl 16) or (this[startIndex + 3].toUInt() shl 24)
}
}
}
fun UByteArray.toInt(startIndex: Int = 0, order: ByteOrder = BIG_ENDIAN) =
toUInt(startIndex, order).toInt()
fun UByteArray.toUIntArray(order: ByteOrder = BIG_ENDIAN) =
UIntArray(size / 4).also { copyInto(it, order = order) }
fun UByteArray.toIntArray(order: ByteOrder = BIG_ENDIAN) =
IntArray(size / 4).also { copyInto(it, order = order) }
fun UByteArray.toULong(startIndex: Int = 0, order: ByteOrder = BIG_ENDIAN): ULong {
require(startIndex in 0..(size - 8))
return when (order) {
BIG_ENDIAN -> {
(this[startIndex].toULong() shl 56) or (this[startIndex + 1].toULong() shl 48) or
(this[startIndex + 2].toULong() shl 40) or (this[startIndex + 3].toULong() shl 32) or
(this[startIndex + 4].toULong() shl 24) or (this[startIndex + 5].toULong() shl 16) or
(this[startIndex + 6].toULong() shl 8) or this[startIndex + 7].toULong()
}
LITTLE_ENDIAN -> {
this[startIndex].toULong() or (this[startIndex + 1].toULong() shl 8) or
(this[startIndex + 2].toULong() shl 16) or (this[startIndex + 3].toULong() shl 24) or
(this[startIndex + 4].toULong() shl 32) or (this[startIndex + 5].toULong() shl 40) or
(this[startIndex + 6].toULong() shl 48) or (this[startIndex + 7].toULong() shl 56)
}
}
}
fun UByteArray.toLong(startIndex: Int = 0, order: ByteOrder = BIG_ENDIAN) =
toULong(startIndex, order).toLong()
fun UByteArray.toULongArray(order: ByteOrder = BIG_ENDIAN) =
ULongArray(size / 8).also { copyInto(it, order = order) }
fun UByteArray.toLongArray(order: ByteOrder = BIG_ENDIAN) =
LongArray(size / 8).also { copyInto(it, order = order) }