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/