Extract a part of a byte array from another byte array. - CSharp System

CSharp examples for System:Byte Array

Description

Extract a part of a byte array from another byte array.

Demo Code


using System.Linq;
using System;//from w  w  w  .  j a va 2s  .  c  o m

public class Main{
        /// <summary>
        ///     Extract a part of a byte array from another byte array.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr">A byte array.</param>
        /// <param name="start">Position to start extraction.</param>
        /// <returns>A part of the given byte array.</returns>
        /// <remarks>code courtesy of @CodesInChaos, public domain</remarks>
        /// <see cref="https://gist.github.com/CodesInChaos/3175971" />
        /// <exception cref="OverflowException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentNullException"></exception>
        public static T[] SubArray<T>(T[] arr, int start)
        {
            return SubArray(arr, start, arr.Length - start);
        }
        /// <summary>
        ///     Extract a part of a byte array from another byte array.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="arr">A byte array.</param>
        /// <param name="start">Position to start extraction.</param>
        /// <param name="length">The length of the extraction started at start.</param>
        /// <returns>A part with the given length of the byte array.</returns>
        /// <remarks>code courtesy of @CodesInChaos, public domain</remarks>
        /// <see cref="https://gist.github.com/CodesInChaos/3175971" />
        /// <exception cref="ArgumentNullException"></exception>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="ArgumentOutOfRangeException"></exception>
        public static T[] SubArray<T>(T[] arr, int start, int length)
        {
            var result = new T[length];
            Buffer.BlockCopy(arr, start, result, 0, length);

            return result;
        }
}

Related Tutorials