主要还是用系统的System.arraycopy来复制相加ByteArray
例子
定义三个ByteArray
val bytes_address = byteArrayOf(
Integer.parseInt("00", 16).toByte(),
Integer.parseInt("60", 16).toByte(),
Integer.parseInt("37", 16).toByte(),
Integer.parseInt("25", 16).toByte(),
Integer.parseInt("a1", 16).toByte(),
Integer.parseInt("f1", 16).toByte(), )
val bytes_payload_header = byteArrayOf(1,1,1,4)
val bytes_payload_firmware = byteArrayOf(0, 0, 0, 0)
传统的相加
val bytes_payload = ByteArray(bytes_payload_header.size + bytes_address.size + bytes_payload_firmware.size)
System.arraycopy(bytes_payload_header, 0, bytes_payload, 0, bytes_payload_header.size)
System.arraycopy(bytes_address, 0, bytes_payload, bytes_payload_header.size, bytes_address.size)
System.arraycopy(bytes_payload_firmware, 0, bytes_payload, bytes_payload_header.size + bytes_address.size, bytes_payload_firmware.size)
println(Arrays.toString(bytes_payload))
结果
[1, 1, 1, 4, 0, 96, 55, 37, -95, -15, 0, 0, 0, 0]
发现是重复操作,还是写个循环来做重复操作吧
val arrayListOf = arrayListOf(bytes_payload_header, bytes_address, bytes_payload_firmware)
val total_size = bytes_payload_header.size + bytes_address.size + bytes_payload_firmware.size
val bytesMerger = bytesMerger(total_size, arrayListOf)
println(Arrays.toString(bytesMerger))
private fun bytesMerger(total_size:Int,arrayListOf: ArrayList<ByteArray>): ByteArray {
val bytes_total = ByteArray(total_size)
var index:Int = 0
for (bytes in arrayListOf) {
System.arraycopy(bytes,0,bytes_total,index,bytes.size)
index +=bytes.size
}
return bytes_total
}
结果
[1, 1, 1, 4, 0, 96, 55, 37, -95, -15, 0, 0, 0, 0]
很简单 记录一下