8

I'm trying to find an easy way to create a mutable byte array that can automatically append any primitive Java data type. I've been searching but could not find anything useful.

I'm looking for something like this

ByteAppender byteStructure = new ByteAppender();
byteStructure.appendInt(5);
byteStructure.appendDouble(10.0);

byte[] bytes = byteStructure.toByteArray();

There is ByteByffer which is great, but you have to know the size of the buffer before you start, which won't work in my case. There is a similar thing (StringBuilder) for creating Strings, but I cannot find one for Bytes.

I thought this would be obvious in Java.

3
  • 2
    Why can't you use an ArrayList<Byte> and use .toArray() afterwards? Commented Jan 17, 2014 at 1:58
  • @JoshM, speed mostly. I have a collection of ordered elements, and for primitive types, I'll just use their bytes. But for strings, I'll need to calculate their length and convert them to a byte array. If I have to calculate the byte array size first, then I have to iterate the list twice, calculating the size on the first pass and then translating on the second. Commented Jan 17, 2014 at 2:01
  • @JeroenVannevel, ArrayList<Byte> doesn't accept primitive types as input, so I would have to constantly do something like this: ByteBuffer.allocate(4).putInt(yourInt).array(); and then for(Byte b : bytes) arrayBytes.add(b);. It is doable but very messy. Commented Jan 17, 2014 at 2:03

1 Answer 1

16

I guess you are looking for java.io.DataOutputStream

ByteArrayOutputStream out = new ByteArrayOutputStream();
DataOutputStream dout = new DataOutputStream(out);
dout.writeInt(1234);
dout.writeLong(123L);
dout.writeFloat(1.2f);
byte[] storingData = out.toByteArray();

How to use storingData?

//how to use storingData?
ByteArrayInputStream in = new ByteArrayInputStream(storingData);
DataInputStream din = new DataInputStream(in);
int v1 = din.readInt();//1234
long v2 = din.readLong();//123L
float v3 = din.readFloat();//1.2f
Sign up to request clarification or add additional context in comments.

2 Comments

Perfect. Exactly what I was looking for.
PS don't forget to close

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.