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

50 lines
1013 B
Kotlin

package com.infendro.bytearray
import com.infendro.bytearray.ByteOrder.BIG_ENDIAN
fun Int.toByteArray(
order: ByteOrder = BIG_ENDIAN,
): ByteArray {
val bytes = ByteArray(4) { i ->
val offset = (3 - i) * 8
(this ushr offset).toByte()
}
return order.normalize(bytes)
}
fun ByteArray.toInt(
order: ByteOrder = BIG_ENDIAN,
): Int {
if (size != 4) throw Exception()
val bytes = order.normalize(this)
return bytes.fold(0) { acc, byte ->
(acc shl 8) or (byte.toInt() and 0xFF)
}
}
fun Collection<Byte>.toInt(
order: ByteOrder = BIG_ENDIAN,
): Int {
return toByteArray()
.toInt(order)
}
fun ByteArray.toIntArray(
order: ByteOrder = BIG_ENDIAN,
): IntArray {
if (size % 4 != 0) throw Exception()
return toList()
.chunked(4)
.map { it.toInt(order) }
.toIntArray()
}
fun Collection<Byte>.toIntArray(
order: ByteOrder = BIG_ENDIAN,
): IntArray {
return toByteArray()
.toIntArray(order)
}