在Kotlin中,将Long转换为uint32字节数组和将Int转换为uint8的最简洁方式是什么?

6
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
}

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

编辑:根据评论修正示例,并演示更改字节顺序。感谢反馈。我将接受演示如何在没有ByteBuffer的情况下完成此操作的答案。


1
myInt.toByte() and 0xFF.toByte() 这样写并没有太多意义。不过,myInt and 0xFF 可能会有用。你不希望结果是一个 Byte,因为 Byte 是有符号的。 - Louis Wasserman
@LouisWasserman 感谢您的审查和发现,Louis。 - A.Sanchez.SD
1
它必须是val bytes = ByteArray(8) - Alexander Egger
1个回答

9

我不喜欢使用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
}

3
为什么在Java中long类型有8个字节大小却要将其转换为4个字节? - Dmitry Kolesnikovich
@DmitryKolesnikovich 看起来他们这样做是为了简单化。将其向右移动24次,与获取最高字节相比,可以获得最高字(虽然我确定你和其他人已经知道了),尽管我不确定我们如何能够将一个字添加到字节数组中。我想这都是个人喜好,我建议将其扩展到包括24、18、16、12、8,并应用0xFF的位掩码,而不是0xFFFF,以防有人想要操作字节而不是字。这样你就可以得到8个字节而不是4个字了。 - Alex Couch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接