denizen
denizen

Reputation: 469

How to Append Bytes to ByteArray in Kotlin

I am a beginner in Kotlin and I was trying to append bytes at the end of a ByteArray. How can I do that ?

Here is one way I tried. Does it look right?

var someByteArray = byteArrayOf(*payload, 0x01.toByte())

where payload is a ByteArray

Your help is much appreciated

Upvotes: 11

Views: 18316

Answers (1)

Kevin Coppock
Kevin Coppock

Reputation: 134664

ByteArray overloads the plus operator, so you can just add to the previous value directly, or assign to a new array. For example:

val startArray = byteArrayOf(0x1, 0x2, 0x3)
val newArray = startArray + 0x4.toByte()

Or if you want to keep the mutable var, you can just plus-assign it:

var array = byteArrayOf(0x1, 0x2, 0x3)
array += 0x4.toByte()

Upvotes: 31

Related Questions