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?
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.
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.
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)
To create a Byte Array in Kotlin, use arrayOf() function. arrayOf() function creates an array of specified type and given elements.
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With