I have two byte arrays and I am wondering how I would go about adding one to the other or combining them to form a new byte array.
byte[] one = getBytesForOne(); byte[] two = getBytesForTwo(); byte[] combined = new byte[one. length + two. length]; System. arraycopy(one,0,combined,0 ,one.
The easiest way to do what you want is a + a[:1] . You could also do a + bytes([a[0]]) . There is no shortcut for creating a single-element bytes object; you have to either use a slice or make a length-one sequence of that byte.
You're just trying to concatenate the two byte
arrays?
byte[] one = getBytesForOne(); byte[] two = getBytesForTwo(); byte[] combined = new byte[one.length + two.length]; for (int i = 0; i < combined.length; ++i) { combined[i] = i < one.length ? one[i] : two[i - one.length]; }
Or you could use System.arraycopy
:
byte[] one = getBytesForOne(); byte[] two = getBytesForTwo(); byte[] combined = new byte[one.length + two.length]; System.arraycopy(one,0,combined,0 ,one.length); System.arraycopy(two,0,combined,one.length,two.length);
Or you could just use a List
to do the work:
byte[] one = getBytesForOne(); byte[] two = getBytesForTwo(); List<Byte> list = new ArrayList<Byte>(Arrays.<Byte>asList(one)); list.addAll(Arrays.<Byte>asList(two)); byte[] combined = list.toArray(new byte[list.size()]);
Or you could simply use ByteBuffer
with the advantage of adding many arrays.
byte[] allByteArray = new byte[one.length + two.length + three.length]; ByteBuffer buff = ByteBuffer.wrap(allByteArray); buff.put(one); buff.put(two); buff.put(three); byte[] combined = buff.array();
You can do this by using Apace common lang package (org.apache.commons.lang.ArrayUtils
class ). You need to do the following
byte[] concatBytes = ArrayUtils.addAll(one,two);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With