How would i translate 2 bytes from and to a UShort...
# getting-started
s
How would i translate 2 bytes from and to a UShort... I'm sure I'm missing something but functions dealing with Unsigned Integers and multiple bytes seems to be lacking from the standard library.
s
correct me if I’m wrong
vice versa you can go from u-short to byte with toByte()
or to unsigned byte with toUByte()
s
So a UShort would be 2 bytes right?
s
I think UShort is in Kotlin 16 bits unsigned int
s
Yeah so i want 2 bytes..
k
(short >> 8).toUByte()
s
yeah that was what I was thinking
does it solve your question @Sam Smallman
?
s
Not really... I'm receiving a ByteArray via Bluetooth, the data I'm interested in is 6 bytes, the first 2 are a UShort, the last 4 are a UInt, I need to be able to translate them back and forth. Maybe I'm missing something but ideally i want something like .toBytes() which will take a UShort and create two signed bytes..
or a toByteArray from a UShort i should say..
and the same for a UInt, and then i can flatten them together.
Copy code
ByteBuffer.wrap(data.sliceArray(0 until 2)).short.toUShort()
ByteBuffer.wrap(data.sliceArray(2 until data.size)).int.toUInt()
This is what i have so far...
and then I've added:
Copy code
fun Short.toByteArray(): ByteArray {
    return ByteBuffer.allocate(2).putShort(this).array()
}
to go along side Int.toByteArray() to go the other way...
s
well if you receive a ByteArray then why can’t you just convert the first 2 bytes to UShort() and the last 4 to UInt() ?