Easy way to concatenate two byte arrays in kotlin?
fun main(args: Array<String>) {
val x = ByteArray(a);
val y = ByteArray(b);
val xLen = x.size
val yLen = y.size
val result = ByteArray(xLen + yLen)
System.arraycopy(x, 0, result, 0, xLen)
System.arraycopy(y, 0, result, xLen, yLen)
// so now result is array that concatenate two byte arrays x,y
}
hope this helps
There is a operator function plus
for ByteArray
(and all other arrays)
operator fun ByteArray.plus(elements: ByteArray): ByteArray
Returns an array containing all elements of the original array and then all elements of the given elements array.
so, you can simply use this function as an operator:
val z ByteArray = x + y
there are also overloaded editions:
operator fun ByteArray.plus(element: Byte): ByteArray
operator fun ByteArray.plus(elements: Collection<Byte>): ByteArray
Please refer this document for details: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/plus.html
BTW, there are many many overloaded editions of this function,
e.g, you can plus a (Iterable<T>
, Collection<T>
, or Array<T>
) and another (Iterable<T>
, Collection<T>
, Array<T>
, or Sequence<T>
), then get a List<T>
,
or you can plus a Set<T>
and another (Array<out T>
, Iterable<T>
, or Sequence<T>
), then get a Set<T>
all these overloaded edition are operator functions, which means you can use it like listA + arrayB
the a + b
operator will invoke operator function a.plus(b)
Please refer this document for details: https://kotlinlang.org/docs/reference/operator-overloading.html