この記事は何?
Kotlin で Int を Big-Endian なバイト配列に変換するプログラムと、Big-Endian なバイト配列を Int に変換するプログラムを掲載しています。
fun Int.toByteArray(): ByteArray {
val array = ByteArray(4)
array[0] = (this shr 24 and 0xFF).toByte()
array[1] = (this shr 16 and 0xFF).toByte()
array[2] = (this shr 8 and 0xFF).toByte()
array[3] = (this and 0xFF).toByte()
return array
}
fun ByteArray.toInt(): Int {
if (this.size != 4) throw IllegalStateException("ByteArray size must be 4, but this is ${this.size}.")
return (this[0].toInt() and 0xFF shl 24) or
(this[1].toInt() and 0xFF shl 16) or
(this[2].toInt() and 0xFF shl 8) or
(this[3].toInt() and 0xFF)
}