在kotlin中连接两个字节数组的简单方法是什么?

时间:2018-06-16 07:05:52

标签: android arrays kotlin

在Kotlin中连接两个字节数组的最简单方法是什么?

考虑,

val x = ByteArray(a);
val y = ByteArray(b);

帮我连接两个字节数组x,y并将其存储在另一个ByteArray中?

2 个答案:

答案 0 :(得分:3)

plus(和所有其他数组)有一个运算符函数ByteArray

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.

因此,您可以简单地将此函数用作运算符:

val z ByteArray = x + y

还有重载版本:

operator fun ByteArray.plus(element: Byte): ByteArray


operator fun ByteArray.plus(elements: Collection<Byte>): ByteArray

有关详细信息,请参阅此文档: https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/plus.html

答案 1 :(得分:2)

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
}

希望这会有所帮助

相关问题