C# merge binary array(byte array)

Lionsure 2020-07-18 Original by the website

Binary arrays are not as easy to add and delete elements as ordinary arrays (such as character arrays) in C#. In the case of adding elements, even if you add an element in front of the array, it can only be achieved by merging the array, which seems a bit troublesome, but limited to C# does not provide the corresponding method.

Merging binary arrays is not like ordinary arrays, only add an array to the back of another array in C#; you need to create a new array, and then add these two arrays to the new array; this is mainly because the array length(That is, the total number of elements) needs to be given when the binary array is created. Then we will see how to use code to merge binary arrays.

 

C# merge binary array(byte array)

First create a new array based on the total length of the array to be merged, then copy the first array to the new array, and then copy the second array to the new array. The implementation code is as follows:

/// <summary>
       /// C# merge binary array
       /// </summary>
       /// <param name="srcArray1">Array 1 to be merged</param>
       /// <param name="srcArray2">Array 2 to be merged</param>
       /// <returns>Merged array</returns>

       private byte[] CombomBinaryArray(byte[] srcArray1, byte[] srcArray2)
       {
              //Create a new array based on the total number of two array elements to be merged
              byte[] newArray = new byte[srcArray1.Length + srcArray2.Length];

       //Copy the first array to the newly created array
              Array.Copy(srcArray1, 0, newArray, 0, srcArray1.Length);

       //Copy the second array to the newly created array
              Array.Copy(srcArray2, 0, newArray, srcArray1.Length, srcArray2.Length);

       return newArray;
       }

Call:

using System.Text;

string text = "C# merge binary array";
       byte[] b1 = Encoding.Default.GetBytes(text);

string words = "C# merge byte array";
       byte[] b2 = Encoding.Default.GetBytes(words);

byte[] newArr = CombomBinaryArray(b1, b2);
       Response.Write("<br />"; + newArr.Length);

 

Output result:

New array length 40