0

I want to convert my result array in ArrayList format to ByteBuffer form.

public ByteBuffer createDNSClientQuestion() {
    ArrayList<Byte> result = new ArrayList<Byte>(QNAME);


    result.add((byte) 0);
    result.add((byte) QTYPE);
    result.add((byte) 0);
    result.add((byte) 1);


    //here, I want to convert result ArrayList to ByteBuffer form and return it. 
}

Any help will be appreciated! Thanks!

Ravi Krishna
  • 67
  • 1
  • 9
  • 2
    Well, have you tried to do anything? Like iterate the list and put the bytes in a buffer? Did it fail? Did you get stuck anywhere? Why write it to a list anyway, instead of directly to a `ByteBuffer`? – RealSkeptic Oct 10 '16 at 09:29
  • Possible duplicate of [Convert ArrayList into a byte\[\]](http://stackoverflow.com/questions/6860055/convert-arraylistbyte-into-a-byte) – Pavneet_Singh Oct 10 '16 at 09:30
  • Please clarify the actual problem you are having with `return new ByteBuffer(4).put(0).put(0).put(QTYPE).put(0);` – Bohemian Oct 10 '16 at 09:42
  • Why? Get rid of the `ArrayList` and put everything directly into a `ByteBuffer`. – user207421 Oct 10 '16 at 09:44
  • problem is QNAME is of ArrayList type and a global variable. I need to modify values in it before adding to ByteBuffer type. Hence I cannot directly use ByteBuffer. – Ravi Krishna Oct 10 '16 at 09:44

1 Answers1

1

You do not need to put interim List to create a ByteBuffer, you can directly put your bytes in a ByteBuffer. Still if you want to go List way, here is how you can do it.

    ArrayList<Byte> result = new ArrayList<Byte>();


    result.add((byte) 0);
    result.add((byte) 2);
    result.add((byte) 0);
    result.add((byte) 1);

    ByteBuffer buffer = ByteBuffer.allocate(result.size());
    for(Byte byt : result) {
        buffer.put(byt);
    }

Hope this helps.

Sanjeev
  • 9,876
  • 2
  • 22
  • 33