我有一个类,Packet我写它来填充一个byte[]516 字节的数组。( ) 为 2 ,packetNum( ) 为 2, ( ) 为 512 。在我的类中有一个方法,它将这些属性组合在一起以创建一个大小为 516 的数组,以发送给收件人:shortauthKeyshortaudiobyte[]Packetbyte[]public byte[] toByteArray() { byte[] fullArray = new byte[516]; ByteBuffer packetNumBuffer = ByteBuffer.allocate(2); packetNumBuffer.putShort(this.packetNum); byte[] packetNumArray = packetNumBuffer.array(); ByteBuffer authKeyBuffer = ByteBuffer.allocate(2); authKeyBuffer.putShort(this.authKey); byte[] authKeyArray = authKeyBuffer.array(); System.arraycopy(packetNumArray, 0, fullArray, 0, packetNumArray.length); System.arraycopy(authKeyArray, 0, fullArray, packetNumArray.length, authKeyArray.length); System.arraycopy(this.audio, 0, fullArray, authKeyArray.length, this.audio.length); return fullArray;}现在,在测试接收到的数据包时, my packetNum(在创建 next 之前递增Packet)已成功传输 - 但是,authKeyandaudio完全错误。这是我的代码的输出,它使用and创建了一个新Packet的:short authKey = 10short packetNum = 0Packet number: 0Auth key = -7936Packet number: 1Auth key = 19201Packet number: 2Auth key = 31490Packet number: 3Auth key = -1Packet number: 4Auth key = -2Packet number: 5Auth key = -3Packet number: 6Auth key = -4Packet number: 7Auth key = -3Packet number: 8Auth key = -2Packet number: 9Auth key = -1Packet number: 10Auth key = 8192auth 密钥为每个数据包吐出随机数,当它应该10用于所有数据包时。这使我相信我的方法没有fullArray按预期填充我的方法。谁能发现我做错了什么?
1 回答
慕的地8271018
TA贡献1796条经验 获得超4个赞
错误就在这里
System.arraycopy(this.audio, 0, fullArray, authKeyArray.length, this.audio.length);
起始位置是authKeyArray.length
但应该是authKeyArray.length + packetNumArray.length
无论如何,System.arraycopy这是绝对避免的方法之一。
我的建议是,使用ByteArrayOutputStream
final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(516);
outputStream.write(packetNumArray);
outputStream.write(authKeyArray);
outputStream.write(audio);
final byte[] fullArray = outputStream.toByteArray();
是不是优雅了很多?
添加回答
举报
0/150
提交
取消