Rob*_*sen 6 arrays byte jvm unsigned-integer kotlin
Kotlin 1.3 引入了无符号整数类型,但我似乎无法弄清楚如何从ByteArrayKotlin JVM 中的a 获取无符号整数。
Kotlin Native 有一个方便的ByteArray.getUIntAt()方法,但是 Kotlin JVM 不存在这个方法。
val bytes: ByteArray = byteArrayOf(1, 1, 1, 1)
val uint: UInt // = ???
Run Code Online (Sandbox Code Playgroud)
我在这里有哪些选择?有没有比使用 aByteBuffer或位移位更优雅的方法呢?
Ale*_*ger 10
正如评论中提到的,在 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))
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5193 次 |
| 最近记录: |