如何使用 ByteBuffer 进行短到 byte[] 的转换?

我有一个类,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 = 0


Packet number: 0

Auth key = -7936

Packet number: 1

Auth key = 19201

Packet number: 2

Auth key = 31490

Packet number: 3

Auth key = -1

Packet number: 4

Auth key = -2

Packet number: 5

Auth key = -3

Packet number: 6

Auth key = -4

Packet number: 7

Auth key = -3

Packet number: 8

Auth key = -2

Packet number: 9

Auth key = -1

Packet number: 10

Auth key = 8192

auth 密钥为每个数据包吐出随机数,当它应该10用于所有数据包时。这使我相信我的方法没有fullArray按预期填充我的方法。谁能发现我做错了什么?


犯罪嫌疑人X
浏览 247回答 1
1回答

慕的地8271018

错误就在这里System.arraycopy(this.audio, 0, fullArray, authKeyArray.length, this.audio.length);起始位置是authKeyArray.length但应该是authKeyArray.length + packetNumArray.length无论如何,System.arraycopy这是绝对避免的方法之一。我的建议是,使用ByteArrayOutputStreamfinal ByteArrayOutputStream outputStream = new ByteArrayOutputStream(516);outputStream.write(packetNumArray);outputStream.write(authKeyArray);outputStream.write(audio);final byte[] fullArray = outputStream.toByteArray();是不是优雅了很多?
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java