リトルエンディアンで、UInt(32bit), UShort(16bit)をByteArrayに変換するコードです。
UInt+.kt
fun UInt.toByteArray(): ByteArray {
val value = this.toInt()
val bytes = ByteArray(4)
bytes[0] = (value and 0xFF).toByte()
bytes[1] = ((value ushr 8) and 0xFF).toByte()
bytes[2] = ((value ushr 16) and 0xFF).toByte()
bytes[3] = ((value ushr 24) and 0xFF).toByte()
return bytes
}
UShort+.kt
fun UShort.toByteArray(): ByteArray {
val value = this.toInt()
val bytes = ByteArray(2)
bytes[0] = (value and 0xFF).toByte()
bytes[1] = ((value ushr 8) and 0xFF).toByte()
return bytes
}