is there a more efficient way to convert 2 bytes t...
# announcements
b
is there a more efficient way to convert 2 bytes to a short in kotlin? i'm worried this is creating a bunch of intermediary types and will be a waste:
Copy code
fun 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.
k
Unless you've determined that there's indeed a performance problem with this code, the JVM should optimize all of this just fine.
In particular
0xFF.toByte()
is some of the easiest stuff to constant fold away.
But I'm not sure what to want
get(byteIndex) and 0xFF.toByte()
to do.
Don't you want something like this instead?
Copy code
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()
}
b
effectively i guess, yeah
at a glance those seem logically equivalent, but maybe i'm missing something
anyway, not too picky on the specifics...i'll just be doing it a lot and wanted to make sure i wasn't allocating additional type instances when it wasn't really needed. i've seen it as an issue in some measurements i'm taking, but not this one specifically. i'll start with this and worry about it later if it ends up being an issue
java isn't picky about the types for shift, etc. so it's just
Copy code
public static short makeShort(byte b1, byte b2)
    {
        return (short)((b1 << 8) | (b2 & 0xFF));
    }
k
You're not allocating here anyway, it all compiles to primitive.
b
ok, great...wasn't sure if there was some boxing going on
k
The problem is that when you just do
.toInt()
the value is sign-extended, if you do that first and then mask
and 0xFF
you should be good.
b
ok, yeah i've actually got a
Byte.toPositiveInt
helper, i removed it to paste in the example
thanks!
k
Ah well that works too of course simple smile
b
and ByteArray.get(index) i assume compiles to byte[index] ?
nm, just confirmed the bytecode...looks like it does
k
Yeah that's literally the
operator fun
you're calling.
594 Views