Stefan Oltmann
05/10/2022, 10:32 AM/**
* Returns an unsigned 16-bit int calculated from the next two bytes of the sequence.
*
* @return the 16 bit int value, between 0x0000 and 0xFFFF
*/
public int getUInt16() {
return (getByte() << 8 & 0xFF00) |
(getByte() & 0xFF);
}
If I add .toInt()
I can use the shl
function, but the result is wrong.
Is there already a standard function for this calculation?Klitos Kyriacou
05/10/2022, 11:15 AM(getByte().toInt() shl 8 and 0xFF00) or (getByte().toInt() and 0xFF)
work for you?msoulatre
05/10/2022, 11:16 AMfun ByteArray.readShort(offset: Int = 0): Int {
return (((this[offset+0].toInt() and 0xff) shl 8) or
((this[offset+1].toInt() and 0xff)))
}
I do wonder if there is a better way with standard functions.Klitos Kyriacou
05/10/2022, 11:18 AMgetByte()
doing? Is it, for example, reading from a ByteBuffer? If so, there's already a getShort()
that does what you want.phldavies
05/10/2022, 11:19 AMByteBuffer
instance (assumedly from the getByte()
calls) then you can do getShort().toUShort()
to get a UShort
, or getShort().toInt() and 0xFFFF
(or getShort().toUShort().toInt()
) to get it as an Int
phldavies
05/10/2022, 11:20 AMStefan Oltmann
05/10/2022, 11:42 AMWhy doesn'tThat works, thank you. I used IDEA automatic Java to Kotlin conversion and overlooked a missing paranthesis. 🙈 I expected the problem somewhere else. 🙄 This is correct:work for you?(getByte().toInt() shl 8 and 0xFF00) or (getByte().toInt() and 0xFF)
fun getUInt16(firstByte: Byte, secondByte: Byte): Int =
firstByte.toInt() shl 8 and 0xFF00 or (secondByte.toInt() and 0xFF)
And this returns the wrong result:
fun getUInt16(firstByte: Byte, secondByte: Byte): Int =
firstByte.toInt() shl 8 and 0xFF00 or secondByte.toInt() and 0xFF
Chris Miller
05/10/2022, 2:28 PMStefan Oltmann
05/10/2022, 2:32 PM