Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to concatenate two byte arrays in kotlin?

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?

like image 327
Steephan Selvaraj Avatar asked Jun 16 '18 07:06

Steephan Selvaraj


Video Answer


2 Answers

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

like image 138
Li Ying Avatar answered Oct 21 '22 15:10

Li Ying


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

like image 32
GianhTran Avatar answered Oct 21 '22 16:10

GianhTran