https://kotlinlang.org logo
#server
Title
# server
g

Gavin Ray

02/11/2023, 6:31 PM
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

jessel

02/11/2023, 6:53 PM
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

CLOVIS

02/11/2023, 7:10 PM
@Gavin Ray your code looks correct, what's your question?
a

Adam S

02/11/2023, 7:25 PM
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

Gavin Ray

02/12/2023, 3:12 PM
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
14 Views