How to concatenate 2 binarybyte arrays in java

I have a 2 byte array:

byte a[i]=1;
byte b[i]=0;

      

I want to combine it so that the output is "10". I am trying to use arraycopy and make new output

byte[] output=a.length+b.length;

      

but it still doesn't work as my expectation. Does anyone know how to solve it?

+3


source to share


3 answers


try it



     byte[] first = {1,2,4,56,6};
     byte[] second = {4,5,7,9,2};
     byte[] merged = new byte[first.length+second.length];

     System.arraycopy(first,0,merged,0,first.length);
     System.arraycopy(second,0,merged,first.length,second.length);
for(int i=0; i<merged.length;i++)
{
    System.out.println(merged[i]);
}

      

+1


source


Try it.



byte[] first = getFirstBytes();
byte[] second = getSecondBytes();

List<Byte> listOfBytes = new ArrayList<Byte>(Arrays.<Byte>asList(first));
listOfBytes.addAll(Arrays.<Byte>asList(second));

byte[] combinedByte = listOfBytes.toArray(new byte[listOfBytes.size()]);

      

+2


source


Try it.

byte a[i] = 1;
byte b[i] = 0;

byte[] output = new byte[a.length + b.length];

for(int i = 0 ; i < output.length ; ++i)
{
    if(i < a.length) output[i] = a[i];
    else output[i] = b[i - a.length];
}

      

+1


source







All Articles