bjonnh
04/29/2020, 7:04 PMmattmoore
04/29/2020, 10:15 PMimport kotlin.experimental.and
Then you can write this as:
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:
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
}
})
mattmoore
04/29/2020, 10:16 PMbjonnh
04/29/2020, 10:23 PMbjonnh
04/29/2020, 10:24 PMmattmoore
04/29/2020, 10:28 PM&
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.bjonnh
04/29/2020, 11:00 PMbjonnh
04/29/2020, 11:10 PMbjonnh
04/29/2020, 11:10 PM