0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Int to ByteArray, ByteArray to Int (Big-Endian)

Posted at

この記事は何?

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)
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?