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

标签 android arrays kotlin byte uint32

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 的情况下执行此操作的答案。

最佳答案

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

关于android - 在 Kotlin 中,将 Long 转换为 uint32 ByteArray 并将 Int 转换为 uint8 的最简洁方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51642947/

相关文章:

android - 自定义 Android 下载服务 - 为每个文件提供进度通知行

arrays - 更快的整数 num2str?

java - 如何在单个 JOptionPane 方法中输出数组的所有值?

javascript - lodash takeRightWhile 从起始索引开始

swift - 使用 Apples CryptoKit 在 iOS 和 Kotlin/Java 之间进行跨平台 AES 加密

java - 使用 sharedPreferences 的 onPause 和 onResume 方法

java - 如何覆盖抽屉导航按钮行为并更改图标?

java - ANDROID:开始另一项 Activity 但没有任何反应

android - 在 Android Kotlin 的 Constraint Layout 中设置适当的约束

android - 如果不为null或为空,则将值作为参数传递