Kotlinでバイトアレイを連結する
この記事では、Kotlinでバイトアレイを連結するさまざまな方法について説明します。
1.使用する +
オペレーター
Kotlinでバイトアレイを連結するための標準的なソリューションは、 +
オペレーター。 2つのアレイのすべての要素を含むアレイを返します。例えば、
1 2 3 4 5 6 7 |
fun main() { val first = "Apple".toByteArray() val second = "Google".toByteArray() val result: ByteArray = first + second println(String(result)) } |
使用することもできます plus()
関数。元のアレイのすべての要素を含み、その後に指定されたアレイのすべての要素が続くアレイを返します。これは、実質的にを使用するのと同じです +
オペレーター。
1 2 3 4 5 6 7 |
fun main() { val first = "Apple".toByteArray() val second = "Google".toByteArray() val result: ByteArray = first.plus(second) println(String(result)) } |
2.使用する ByteArrayOutputStream
ここでの考え方は、各バイトアレイから出力ストリームにバイトを書き込み、 toByteArray()
出力ストリームの内容をバイトアレイとして取得する関数。これは、varargを使用してKotlinで次のように実装できます。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import java.io.ByteArrayOutputStream fun concat(vararg arrays: ByteArray): ByteArray { val out = ByteArrayOutputStream() arrays.forEach { out.write(it) } return out.toByteArray() } fun main() { val first = "Apple".toByteArray() val second = ", ".toByteArray() val third = "Google".toByteArray() val result = concat(first, second, third) println(String(result)) } |
出力:
Apple, Google
3.使用する ByteBuffer
別の解決策は、 ByteBuffer#put()
各バイトアレイからバッファにバイトを転送し、を呼び出す関数 array()
バッファからバイトアレイを取得する関数。
1 2 3 4 5 6 7 8 9 10 11 12 |
import java.nio.ByteBuffer fun main() { val first = "Apple".toByteArray() val second = "Google".toByteArray() val result = ByteBuffer.allocate(first.size + second.size) .put(first) .put(second) .array() println(String(result)) } |
出力:
AppleGoogle
任意の数のバイトアレイを連結するには、varargsを受け取るユーティリティ関数を作成します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import java.nio.ByteBuffer fun concat(vararg arrays: ByteArray): ByteArray { val n = arrays.map {it.size}.sum() val byteBuffer = ByteBuffer.allocate(n) arrays.forEach { byteBuffer.put(it) } return byteBuffer.array() } fun main() { val first = "Apple".toByteArray() val second = ", ".toByteArray() val third = "Google".toByteArray() val result = concat(first, second, third) println(String(result)) } |
出力:
Apple, Google
4.使用する System.arraycopy()
関数
もう1つのエレガントな解決策は、 System.arraycopy()
、アレイの内容を宛先アレイに効率的にコピーできます。完全なコードは次のとおりです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
fun concat(vararg arrays: ByteArray): ByteArray { val len = arrays.map { it.size }.sum() val result = ByteArray(len) var lengthSoFar = 0 for (array in arrays) { System.arraycopy(array, 0, result, lengthSoFar, array.size) lengthSoFar += array.size } return result } fun main() { val first = "Apple".toByteArray() val second = ", ".toByteArray() val third = "Google".toByteArray() val result = concat(first, second, third) println(String(result)) } |
出力:
Apple, Google
Kotlinでバイトアレイを連結する方法は以上です。