在 Kotlin 中,将 Long 转换为 uint32 ByteArray 并将 Int 转换为 uint8 的最简洁方法是什么?

A.S*_*.SD 4 arrays android byte uint32 kotlin

fun longToByteArray(value: Long): ByteArray {
    val bytes = ByteArray(8)
    ByteBuffer.wrap(bytes).putLong(value)
    return Arrays.copyOfRange(bytes, 4, 8)
}

fun intToUInt8(value: Int): ByteArray {
    val bytes = ByteArray(4)
    ByteBuffer.wrap(bytes).order(ByteOrder.LITTLE_ENDIAN).putInt(value and 0xff)
    var array = Arrays.copyOfRange(bytes, 0, 1)
    return array
}
Run Code Online (Sandbox Code Playgroud)

我认为这些是一些 Java 方法的 Kotlin 等价物,但我想知道这些方法在 Kotlin 中是否正确/必要。

编辑:根据评论修复示例,还演示了不断变化的字节顺序。感谢您的反馈。我将接受演示如何在没有 ByteBuffer 的情况下执行此操作的答案。

Ale*_*ger 7

我不喜欢使用,ByteBuffer因为它增加了对 JVM 的依赖。相反,我使用:

fun longToUInt32ByteArray(value: Long): ByteArray {
    val bytes = ByteArray(4)
    bytes[3] = (value and 0xFFFF).toByte()
    bytes[2] = ((value ushr 8) and 0xFFFF).toByte()
    bytes[1] = ((value ushr 16) and 0xFFFF).toByte()
    bytes[0] = ((value ushr 24) and 0xFFFF).toByte()
    return bytes
}
Run Code Online (Sandbox Code Playgroud)

  • 如果 Java 中 long 的大小为 8 个字节,为什么要将 long 转换为 4 个字节? (3认同)