How can I insert (not replace) a byte at zero inde...
# getting-started
o
How can I insert (not replace) a byte at zero index in ByteArray ?
d
Assuming the existing array is already full: Make a new ByteArray with length equal to your current ByteArray + 1. Use
System.arrayCopy()
to copy the existing ByteArray into the new ByteArray starting at index 1. Set index 0 equal to your new value. Note that if performance is a concern you probably want to figure out a way to avoid doing this operation.
👌 4
d
Instead of
System.arraycopy
(which will work) you should use
oldArray.copyInto
which is available in the kotlin stdlib on all platforms.
On the other hand, the easy dirty way would be to use
val newArray = byteArrayOf(elemToAdd, *oldArray)
.