Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get an unsigned integer from a byte array in Kotlin JVM?

Kotlin 1.3 introduced unsigned integer types, but I can't seem to figure out how to get an unsigned integer from a ByteArray in Kotlin JVM.

Kotlin Native has a convenient ByteArray.getUIntAt() method, but this does not exist for Kotlin JVM.

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

What are my options here? Is there a more elegant way than using a ByteBuffer, or bit-shifting my way out of this?

like image 601
Robby Cornelissen Avatar asked Dec 26 '18 07:12

Robby Cornelissen


People also ask

Is byte in Java unsigned?

In Java, byte is data type. It is 8-bit signed (+ ive or - ive) values from -128 to 127. The range of unsigned byte is 0 to 255. Note that Java does not provide unsigned byte.

What is unsigned byte array?

For unsigned byte , the allowed values are from 0 to 255 . Java doesn't have unsigned bytes (0 to 255). To make an unsigned byte, we can cast the byte into an int and mask (bitwise and) the new int with a 0xff to get the last 8 bits or prevent sign extension.

What is UInt in Kotlin?

UInt is an unsigned 32-bit integer (0 to 2^32 – 1) The kotlin. ULong is an unsigned 64-bit integer (0 to 2^64 -1)

How do you use Bytearray Kotlin?

To create a Byte Array in Kotlin, use arrayOf() function. arrayOf() function creates an array of specified type and given elements.


1 Answers

As mentioned in the comments there is no out of the box solution in the JVM version of Kotlin. An extension function doing the same as the Kotlin/Native function might look like this:

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))
}
like image 133
Alexander Egger Avatar answered Sep 20 '22 10:09

Alexander Egger