Tsakiroglou Fotis
Tsakiroglou Fotis

Reputation: 1031

ByteBuffer seems out of Bounds

I am trying to read a short array , convert its elements and put them into a byte array.I use ByteBuffer and I take back this Exception :

Exception in thread "main" java.lang.IndexOutOfBoundsException I tried to alter the .allocateDirect up to 16 but got the same. I tried both ByteBuffer.allocateDirect(2) and 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");
       }}}

I know that a short doesnt fit in a single unsigned byte but i will build some defence later to read shorts up to 255.

Upvotes: 0

Views: 519

Answers (1)

Abdelhak
Abdelhak

Reputation: 8387

I think this code can help you to understand some thing.

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");
    }
}
}

Upvotes: 1

Related Questions