gpt4 book ai didi

java - ByteBuffer 似乎超出范围

转载 作者:行者123 更新时间:2023-12-01 10:52:10 27 4
gpt4 key购买 nike

我正在尝试读取一个短数组,转换其元素并将它们放入字节数组中。我使用 ByteBuffer 并收回此异常:

线程“main”中的异常 java.lang.IndexOutOfBoundsException我尝试将 .allocateDirect 更改为 16,但得到的结果相同。我尝试了 ByteBuffer.allocateDirect(2) 和 ByteBuffer.allocate(2)

public class int2byte {
short[] it = new short[4];
byte[] by = new byte[4];
public static void main(String [] args){
int2byte Convert=new int2byte();
Convert.start();
}
public void start(){
it = new short[]{192,168, 1,2};


ByteBuffer bytBuff = ByteBuffer.allocateDirect(2);
for(int i=0;i<3;i++){

bytBuff.putShort(it[i]);
by[i]=bytBuff.get(it[i]);
System.out.print("I get " + by[i]+ "\n\n");
}}}

我知道 Short 不适合单个无符号字节,但稍后我会构建一些防御来读取最多 255 个 Short 。

最佳答案

我认为这段代码可以帮助你理解一些事情。

public class Test {
short[] it = new short[4];
byte[] by = new byte[4];

public static void main(String[] args) {
Test Convert = new Test();
Convert.start();
}

public void start() {
it = new short[] { 192, 168, 1, 2 };

ByteBuffer bytBuff = ByteBuffer.allocateDirect(2000);
for (int i = 0; i < it.length; i++) {

bytBuff.putShort(it[i]);
by[i] = bytBuff.get(i);
System.out.print("I get byte " + by[i] + "\n\n");
System.out.print("I get short " + it[i] + "\n\n");
System.out.print("I get buffer " + bytBuff.get(i) + "\n\n");
}
}
}

关于java - ByteBuffer 似乎超出范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33802451/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com