arrays - 如何从 Kotlin JVM 的字节数组中获取无符号整数?

标签 arrays kotlin jvm byte unsigned-integer

Kotlin 1.3 引入 unsigned integer types ,但我似乎无法弄清楚如何从 ByteArray 中获取无符号整数在 Kotlin JVM 中。

Kotlin Native 有一个方便的 ByteArray.getUIntAt() 方法,但这对于 Kotlin JVM 不存在。

val bytes: ByteArray = byteArrayOf(1, 1, 1, 1)
val uint: UInt // = ???

我在这里有哪些选择?有没有比使用 ByteBuffer 更优雅的方法? ,或者改变我的出路?

最佳答案

正如评论中提到的,在 Kotlin 的 JVM 版本中没有开箱即用的解决方案。与 Kotlin/Native 函数执行相同操作的扩展函数可能如下所示:

fun ByteArray.getUIntAt(idx: Int) =
    ((this[idx].toUInt() and 0xFFu) shl 24) or
            ((this[idx + 1].toUInt() and 0xFFu) shl 16) or
            ((this[idx + 2].toUInt() and 0xFFu) shl 8) or
            (this[idx + 3].toUInt() and 0xFFu)

fun main(args: Array<String>) {

    // 16843009
    println(byteArrayOf(1, 1, 1, 1).getUIntAt(0))

    // 4294967295, which is UInt.MAX_VALUE
    println(byteArrayOf(-1, -1, -1, -1).getUIntAt(0))
}

关于arrays - 如何从 Kotlin JVM 的字节数组中获取无符号整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53929025/

相关文章:

php - Mysql 查询似乎可以工作,但仍然出现错误?

java - eclipse.ini 是用于我从 Eclipse 编译和启动的 Java 应用程序还是用于 IDE 本身?

scala - 从源码安装 sbt

MySQL按数组值排序

arrays - 如何在 Swift 中将数组中的值分配给按钮

javascript - 为唯一元素过滤对象数组

android - Room "cannot find implementation for"即使使用 kapt

android - kotlin中如何将Unit转换为String(添加同步代码后UPD不起作用)

java - Google Play服务游戏signInSilently()失败错误 'com.google.android.gms.common.api.ApiException: 4: 4 '

garbage-collection - JNI 代码即与垃圾收集并发执行。