我正在尝试读取一个短数组,转换其元素并将它们放入一个字节数组中。我使用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");
}}}
我知道短的不适合单个无符号字节,但我稍后会建立一些防御来读取最多255个短消息。
答案 0 :(得分:1)
我认为这段代码可以帮助您理解一些事情。
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");
}
}
}