If I have a well-formed ByteArray
(say, byteArrayOf(12, 0, 24, 0)
), what is the easiest way to convert this into a ShortArray
?
For simplicity's sake, assume little-endian unless endianness handling is easy too.
Resultant ShortArray
should look like (12, 24)
.
You can process the ByteArray
as a list with .chunked()
, though you have to manually convert the two bytes into a Short
:
val bytes = byteArrayOf(12, 0, 24, 0)
val shorts = bytes
.asList()
.chunked(2)
.map { (l, h) -> (l.toInt() + h.shl(8)).toShort() }
.toShortArray()
I'm not certain why, but it appears that Kotlin treats bytes as if they are signed and the above answer work only when the first byte of each pair is < 127.
For example (editing the above to return correct answers):
val byteArray = byteArrayOf(211.toByte(), 0, 24, 0)
val shortArray = ShortArray(byteArray.size / 2) {
(byteArray[it * 2].toUByte().toInt() + (byteArray[(it * 2) + 1].toInt() shl 8)).toShort()
}
println(shortArray.toList()) // [211, 24]
Using the above code with the same values returns incorrect information as [-45, 24]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With