【问题标题】:In Kotlin, whats the cleanest way to convert a Long to uint32 ByteArray and an Int to uint8?在 Kotlin 中,将 Long 转换为 uint32 ByteArray 并将 Int 转换为 uint8 的最简洁方法是什么?
【发布时间】:2018-08-01 22:13:23
【问题描述】:
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 中是否正确/必要。

编辑:修复每个 cmets 的示例,还演示了更改字节顺序。感谢您的反馈。我将接受演示如何在没有 ByteBuffer 的情况下执行此操作的答案。

【问题讨论】:

  • myInt.toByte() and 0xFF.toByte() 没有多大意义。不过,myInt and 0xFF 可能会。您不希望结果是Byte,因为Byte 是固有签名的。
  • @LouisWasserman 感谢您查看并关注此 Louis。
  • 必须是val bytes = ByteArray(8)

标签: android arrays kotlin byte uint32


【解决方案1】:

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

【讨论】:

  • 如果Java中long的大小为8字节,为什么要将long转换为4字节?
  • @DmitryKolesnikovich 看起来他们这样做是为了简单。与获得最高字节相比,将它向右移动 24 次可以得到最高的字(尽管我相信您和其他人已经知道这一点),尽管我不确定我们如何能够将一个字添加到字节数组中。我猜这是所有偏好,我建议将其扩展为包括 24、18、16、12、8 并应用 0xFF 而不是 0xFFFF 的位掩码,以防有人想对字节而不是单词进行操作。这样你得到 8 个字节而不是 4 个字。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-05
  • 2011-03-01
  • 2017-02-20
  • 1970-01-01
  • 1970-01-01
  • 2011-09-23
  • 1970-01-01
相关资源
最近更新 更多