Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a ByteArray to a ShortArray in Kotlin?

Tags:

arrays

kotlin

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).

like image 813
Brendan Molloy Avatar asked Jan 28 '23 05:01

Brendan Molloy


2 Answers

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()
like image 94
hotkey Avatar answered Jan 31 '23 10:01

hotkey


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]

like image 21
Kenneth Argo Avatar answered Jan 31 '23 09:01

Kenneth Argo