2

I have a byte array. But I want array length mod 4=0. So I want to add 00 after array until pass condition. I find many solutions to append array

byte[] arr_combined = new byte[arr_1.length + arr_2.length];
System.arraycopy(arr_1, 0, arr_combined, 0, arr_1.length);
System.arraycopy(arr_2, 0, arr_combined, arr_1.length, arr_2.length);

But I do not want to create new byte array. I only want append byte after a byte array. Thanks

3
  • 2
    Arrays have a fixed length. if you want to append and change size, use a List Commented Jun 11, 2015 at 9:22
  • I would calculate the prefered length, use that result to create a new array, and fill in the data. Commented Jun 11, 2015 at 9:24
  • As Dragondraikk said, use a List, once you're done convert it to an Array. It will be much easier. Commented Jun 11, 2015 at 9:30

2 Answers 2

4

As it was already mentioned, Java arrays have fixed size which cannot be changed after array is created. In your case it's probably ok to use ByteArrayOutputStream:

ByteArrayOutputStream out = new ByteArrayOutputStream();
out.write(arr_1);
out.write(arr_2);
byte[] arr_combined = out.toByteArray();

This way you work with primitive byte type (unlike List<Byte>) which will be more efficient. The drawback is that ByteArrayOutputStream is synchronized, so there's some overhead for synchronization (though I guess it's much lower than boxing/unboxing overhead when using List<Byte>). Another drawback is that ByteArrayOutputStream.write is declared to throw IOException. In practice it's never thrown, but you have to catch/rethrow it.

If you don't mind using third-party libraries, there are plenty ways to create convenient wrappers over the primitive types which don't have these drawbacks. For example, TByteArrayList from Trove library.

Sign up to request clarification or add additional context in comments.

Comments

0

If you have an array you can't modify the length of it. You should use an ArrayList:

List<Byte> bytes = new ArrayList<Byte>();

Here you can add a new element wherever you want just using add method so, supposing that b it's a byte variable:

bytes.add(b);

So, in this way, you can add the number of 00 that you want regardless of the length of the ArrayList.

EDIT: I saw now on this question that you can convert the ArrayList when you have complete it to an array, like this:

Byte[] arrayBytes = bytes.toArray(new Byte[bytes.size()]);

I expect it helps to you!

2 Comments

how can Byte[] be converted to byte[]?
@ArthurEirich if you have an array of byte[] called newBytes you can do this: newBytes.toPrimitive(arrayBytes,//Here the value to set if it is null);

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.