how do you write that in kotlin?
# chicago
b
how do you write that in kotlin?
m
@bjonnh https://kotlinlang.org/docs/reference/basic-types.html#operations If you import
import kotlin.experimental.and
Then you can write this as:
Copy code
return ((b[3] and 0xff.toByte()).toLong() shl 24) or ((b[2] and 0xff.toByte()).toLong() shl 16) or ((b[1] and 0xff.toByte()).toLong() shl 8) or (b[0] and 0xff.toByte()).toLong()
To make it a little clearer:
Copy code
package io.mattmoore.kotlin.standard

import io.kotest.core.spec.style.StringSpec
import io.kotest.matchers.shouldBe
import kotlin.experimental.and

class ByteOperationsSpec : StringSpec({
    "bit operations in Kotlin" {
        fun getUnsignedIntLE(b: ByteArray): Long {
            val first = (b[3] and 0xff.toByte()).toLong() shl 24
            val second = (b[2] and 0xff.toByte()).toLong() shl 16
            val third = (b[1] and 0xff.toByte()).toLong() shl 8
            val fourth = (b[0] and 0xff.toByte()).toLong()
            return first or second or third or fourth

// or for a really long line...
//            return ((b[3] and 0xff.toByte()).toLong() shl 24) or ((b[2] and 0xff.toByte()).toLong() shl 16) or ((b[1] and 0xff.toByte()).toLong() shl 8) or (b[0] and 0xff.toByte()).toLong()
        }

        val input = listOf(20, 10, 30, 5)
                .map { it.toByte() }
                .toByteArray()
        val result = getUnsignedIntLE(input)
        result shouldBe 85854740
    }
})
This is actually a scenario where I feel Java is a little easier on the eyes for these operations than Kotlin ūü§£ - that's not usually the case.
b
yeah I was really surprised byte manipulation is so painful
I read that internally in java everything is turned into Int
m
This is possibly a case where compiler plugin with Arrow Meta would be useful to allow for writing
&
and
|
and then having Meta rewrite the syntax into the extension functions. I'm actually working on some compiler plugin stuff lately so I might throw something together for this as well. It would allow you to basically do bit operations the same way you can in Java.
b
also the support of unsigned long is …
oh there is that in experimental
good