bbaldino
03/11/2019, 7:50 PMfun ByteArray.getShort(byteIndex: Int): Short {
val b1 = (get(byteIndex) and 0xFF.toByte()).toInt()
val b2 = (get(byteIndex + 1) and 0xFF.toByte()).toInt()
return ((b1 shl 8 ) or (b2)).toShort()
}
i could keep static instances of the masks (0xFF.toByte()
) but i still have to create the Ints which seems like a waste.karelpeeters
03/11/2019, 7:59 PM0xFF.toByte()
is some of the easiest stuff to constant fold away.get(byteIndex) and 0xFF.toByte()
to do.fun ByteArray.getShort(byteIndex: Int): Short {
val b1 = this[byteIndex].toInt() and 0xFF
val b2 = this[byteIndex + 1].toInt() and 0xFF
return ((b1 shl 8) + b2).toShort()
}
bbaldino
03/11/2019, 8:05 PMpublic static short makeShort(byte b1, byte b2)
{
return (short)((b1 << 8) | (b2 & 0xFF));
}
karelpeeters
03/11/2019, 8:08 PMbbaldino
03/11/2019, 8:08 PMkarelpeeters
03/11/2019, 8:09 PM.toInt()
the value is sign-extended, if you do that first and then mask and 0xFF
you should be good.bbaldino
03/11/2019, 8:10 PMByte.toPositiveInt
helper, i removed it to paste in the examplekarelpeeters
03/11/2019, 8:11 PMbbaldino
03/11/2019, 8:12 PMkarelpeeters
03/11/2019, 8:14 PMoperator fun
you're calling.