Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 673
denizen Avatar asked Mar 19 '19 22:03

denizen


1 Answers

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()
like image 156
Kevin Coppock Avatar answered Oct 24 '22 13:10

Kevin Coppock