What is the easiest way to concatenate two byte arrays in Kotlin?
Consider,
val x = ByteArray(a);
val y = ByteArray(b);
Help me to concatenate two byte arrays x,y
and store it in another ByteArray
?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With