Concatenate two byte arrays. - CSharp System

CSharp examples for System:Byte Array

Description

Concatenate two byte arrays.

Demo Code


using System.Linq;
using System;// w  w w.  j  a v a2s .co  m

public class Main{
        /// <summary>
        ///     Concatenate two byte arrays.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr1">The first byte array.</param>
        /// <param name="arr2">The second byte array.</param>
        /// <returns>The concatenated byte arrays.</returns>
        /// <remarks>code courtesy of @CodesInChaos, public domain</remarks>
        /// <see cref="https://gist.github.com/CodesInChaos/3175971" />
        /// <exception cref="OverflowException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static T[] ConcatArrays<T>(T[] arr1, T[] arr2)
        {
            checked
            {
                var result = new T[arr1.Length + arr2.Length];
                Buffer.BlockCopy(arr1, 0, result, 0, arr1.Length);
                Buffer.BlockCopy(arr2, 0, result, arr1.Length, arr2.Length);

                return result;
            }
        }
        /// <summary>
        ///     Concatenate the given byte arrays.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arrays">The byte arrays.</param>
        /// <returns>The concatenated byte arrays.</returns>
        /// <remarks>code courtesy of @CodesInChaos, public domain</remarks>
        /// <see cref="https://gist.github.com/CodesInChaos/3175971" />
        /// <exception cref="OverflowException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static T[] ConcatArrays<T>(params T[][] arrays)
        {
            checked
            {
                var result = new T[arrays.Sum(arr => arr.Length)];
                var offset = 0;

                foreach (var arr in arrays)
                {
                    Buffer.BlockCopy(arr, 0, result, offset, arr.Length);
                    offset += arr.Length;
                }

                return result;
            }
        }
}

Related Tutorials