https://kotlinlang.org logo
#getting-started
Title
# getting-started
s

Sam Smallman

07/07/2020, 2:13 PM
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

stephanmg

07/07/2020, 2:19 PM
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

Sam Smallman

07/07/2020, 2:22 PM
So a UShort would be 2 bytes right?
s

stephanmg

07/07/2020, 2:22 PM
I think UShort is in Kotlin 16 bits unsigned int
s

Sam Smallman

07/07/2020, 2:30 PM
Yeah so i want 2 bytes..
k

Kroppeb

07/07/2020, 4:00 PM
(short >> 8).toUByte()
s

stephanmg

07/07/2020, 4:01 PM
yeah that was what I was thinking
does it solve your question @Sam Smallman
?
s

Sam Smallman

07/07/2020, 4:06 PM
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

stephanmg

07/08/2020, 7:34 AM
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() ?
3 Views