Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 370
Denis Avatar asked Oct 17 '25 01:10

Denis


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)
like image 194
Denis Avatar answered Oct 19 '25 17:10

Denis


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

like image 24
a_local_nobody Avatar answered Oct 19 '25 19:10

a_local_nobody