第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問(wèn)題,去搜搜看,總會(huì)有你想問(wèn)的

如何使用 ByteBuffer 進(jìn)行短到 byte[] 的轉(zhuǎn)換?

如何使用 ByteBuffer 進(jìn)行短到 byte[] 的轉(zhuǎn)換?

犯罪嫌疑人X 2022-07-20 16:15:43
我有一個(gè)類,Packet我寫它來(lái)填充一個(gè)byte[]516 字節(jié)的數(shù)組。( ) 為 2 ,packetNum( ) 為 2, ( ) 為 512 。在我的類中有一個(gè)方法,它將這些屬性組合在一起以創(chuàng)建一個(gè)大小為 516 的數(shù)組,以發(fā)送給收件人: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;}現(xiàn)在,在測(cè)試接收到的數(shù)據(jù)包時(shí), my packetNum(在創(chuàng)建 next 之前遞增Packet)已成功傳輸 - 但是,authKeyandaudio完全錯(cuò)誤。這是我的代碼的輸出,它使用and創(chuàng)建了一個(gè)新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 密鑰為每個(gè)數(shù)據(jù)包吐出隨機(jī)數(shù),當(dāng)它應(yīng)該10用于所有數(shù)據(jù)包時(shí)。這使我相信我的方法沒有fullArray按預(yù)期填充我的方法。誰(shuí)能發(fā)現(xiàn)我做錯(cuò)了什么?
查看完整描述

1 回答

?
慕的地8271018

TA貢獻(xiàn)1796條經(jīng)驗(yàn) 獲得超4個(gè)贊

錯(cuò)誤就在這里


System.arraycopy(this.audio, 0, fullArray, authKeyArray.length, this.audio.length);

起始位置是authKeyArray.length

但應(yīng)該是authKeyArray.length + packetNumArray.length


無(wú)論如何,System.arraycopy這是絕對(duì)避免的方法之一。

我的建議是,使用ByteArrayOutputStream


final ByteArrayOutputStream outputStream = new ByteArrayOutputStream(516);

outputStream.write(packetNumArray);

outputStream.write(authKeyArray);

outputStream.write(audio);

final byte[] fullArray = outputStream.toByteArray();

是不是優(yōu)雅了很多?


查看完整回答
反對(duì) 回復(fù) 2022-07-20
  • 1 回答
  • 0 關(guān)注
  • 306 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購(gòu)課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)