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

Hu hu
  • 49
  • 1
  • 1
  • 5

2 Answers2

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.

Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
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!

Community
  • 1
  • 1
Francisco Romero
  • 12,787
  • 22
  • 92
  • 167