How can I convert a ByteArray to an Int with Kotlin?

Viewed 302

How can I convert a ByteArray to an Int with Kotlin?

The code I was using in Java :

return ((buffer[offset++] & 0xff) << 24) |
       ((buffer[offset++] & 0xff) << 16) |
       ((buffer[offset++] & 0xff) << 8) |
       (buffer[offset] & 0xff);

I tried this code in Kotlin :

return (buffer[offset++] and 0xff shl 24) or
       (buffer[offset++] and 0xff shl 16) or
       (buffer[offset++] and 0xff shl 8) or
       (buffer[offset] and 0xff)

But it returns the following warning regarding the "and" operator :

None of the following candidates is applicable because of receiver type mismatch

2 Answers

Thanks to @a_local_nobody, I managed to fix the problem :

return (buffer[offset++].toInt() and 0xff shl 24) or
        (buffer[offset++].toInt() and 0xff shl 16) or
        (buffer[offset++].toInt() and 0xff shl 8) or
        (buffer[offset].toInt() and 0xff)

I did some reading, seems like Bitwise operations like and, or, and shl are only defined for Int and Long in Kotlin.

from the docs:

enter image description here

You'll have to convert these if you want to use them

Related