LoginSignup
4
3

More than 3 years have passed since last update.

KotlinでByteArrayをLong, Intに変換する

Last updated at Posted at 2018-11-22

バイトオーダーがBigEndianであることを前提にしています。

JVM環境の場合

JVM環境ではByteBufferクラスが使えるので、簡単にByteArrayを数値に変換することができます

jvm.kt
// ByteArray -> Long
val longBytes = byteArrayOf(1, 1, 1, 1, 1, 1, 1, 1)
ByteBuffer.wrap(longBytes).getLong()

// ByteArray -> Int
val intBytes = byteArrayOf(1, 1, 1, 1)
ByteBuffer.wrap(intBytes).getInt()

Kotlin/Native環境の場合

Kotlin/Native環境の場合はByteBufferクラスが使えないので、以下のような関数を実装します。

native.kt
// 8バイトの配列をLong型に変換します。
fun byteArrayToLong(byteArray: ByteArray?): Long {
    byteArray ?: return 0
    var result: Long = 0
    for (i in 0..7) {
        val value = byteArray.getOrNull(i) ?: 0
        result = result shl 8
        result = result or value.toUByte().toLong()
    }
    return result
}

// 4バイトの配列をInt型に変換します。
fun byteArrayToInt(byteArray: ByteArray?): Int {
    byteArray ?: return 0
    var result = 0
    for (i in 0..3) {
        result = result shl 8
        result = result or byteArray[i].toUByte().toInt()
    }
    return result
}

テスト

test.kt
import kotlin.experimental.and
import java.nio.ByteBuffer

// 8バイトの配列をLong型に変換します。
fun byteArrayToLong(byteArray: ByteArray): Long {
    var result: Long = 0
    for (i in 0..7) {
        result = result shl 8
        result = result or (byteArray[i] and 0xFF.toByte()).toLong()
    }
    return result
}

// 4バイトの配列をInt型に変換します。
fun byteArrayToInt(byteArray: ByteArray): Int {
    var result: Int = 0
    for (i in 0..3) {
        result = result shl 8
        result = result or (byteArray[i] and 0xFF.toByte()).toInt()
    }
    return result
}

fun main(args: Array<String>){  
    val longBytes = byteArrayOf(1, 1, 1, 1, 1, 1, 1, 1)
    val intBytes = byteArrayOf(1, 1, 1, 1)

    println("ByteBuffer#getLong(): ${ByteBuffer.wrap(longBytes).getLong()}")
    println("ByteBuffer#getInt(): ${ByteBuffer.wrap(intBytes).getInt()}")

    println("byteArrayToLong(): ${byteArrayToLong(longBytes)}")
    println("byteArrayToInt(): ${byteArrayToInt(intBytes)}")
}

実行結果

[Running] cd "/Users/hoge" && kotlinc-jvm test.kt -include-runtime -d test.jar && java -jar test.jar
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
Picked up JAVA_TOOL_OPTIONS: -Dfile.encoding=UTF-8
ByteBuffer#getLong(): 72340172838076673
ByteBuffer#getInt(): 16843009
byteArrayToLong(): 72340172838076673
byteArrayToInt(): 16843009

参考

4
3
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
4
3