代码之家  ›  专栏  ›  技术社区  ›  Robby Cornelissen

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

  •  1
  • Robby Cornelissen  · 技术社区  · 7 年前

    介绍了Kotlin 1.3 unsigned integer types ,但我似乎不知道如何从 ByteArray

    科特林本地人有一个方便的 ByteArray.getUIntAt() 方法,但这对于Kotlin JVM不存在。

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

    ByteBuffer 或是有点改变我的想法?

    1 回复  |  直到 7 年前
        1
  •  11
  •   Alexander Egger    7 年前

    如评论中所述,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))
    }