Is it possible to create an operator function to o...
# server
g
Is it possible to create an operator function to overload
[from .. to]
on
ByteArray
to do something like this?
Copy code
operator fun ByteArray.get(intRange: IntRange): Byte {
    val bytes = this.sliceArray(intRange)
    return ByteBuffer.wrap(bytes).getInt()
}

fun getID(data: ByteArray): Int = data[0..3] as Int
j
You could get nearly this by specifying the from and to variables as parameters of the
get
operator
operator fun ByteArray.get(from: Int, to: Int)
data[0, 3]
c
@Gavin Ray your code looks correct, what's your question?
a
yeah, it needs a bit of tidying (I’m not sure what the ByteBuffer is for) but the general idea seems to work https://pl.kotl.in/4zSqCQ0ap
Copy code
fun main() {
	val bytes = byteArrayOf(0x1, 0x2, 0x3, 0x4, 0x5)
    println(bytes[1..3].joinToString())
    println(bytes[4..4].joinToString())
    println(bytes[0..4].joinToString())
}

operator fun ByteArray.get(intRange: IntRange) = this.sliceArray(intRange)
Copy code
2, 3, 4
5
1, 2, 3, 4, 5
g
Ahh okay thank you -- I was running into issues because it was returning a
Byte
type rather than an
Int
but this is great -- thanks all!
👍 1