Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine two byte arrays [duplicate]

Tags:

java

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.

like image 670
novicePrgrmr Avatar asked Apr 16 '11 00:04

novicePrgrmr


People also ask

How do you merge bytes in Java?

byte[] one = getBytesForOne(); byte[] two = getBytesForTwo(); byte[] combined = new byte[one. length + two. length]; System. arraycopy(one,0,combined,0 ,one.

How do you concatenate bytes in Python?

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.


2 Answers

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(); 
like image 174
pickypg Avatar answered Sep 23 '22 04:09

pickypg


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); 
like image 37
CJPro Avatar answered Sep 26 '22 04:09

CJPro