Slice a byte array - CSharp System

CSharp examples for System:Byte Array

Description

Slice a byte array

Demo Code

// Copyright (c) Microsoft. All rights reserved.
using System.Diagnostics.Contracts;
using System;//from  w ww.  ja v a  2  s .co  m

public class Main{
        public static byte[] Slice(this byte[] array, int index, int length)
        {
            Contract.Requires(array != null);

            if (index + length > array.Length)
            {
                throw new ArgumentOutOfRangeException("length", string.Format("index: ({0}), length({1}) index + length cannot be longer than Array.length({2})", index, length, array.Length));
            }
            var result = new byte[length];
            Array.Copy(array, index, result, 0, length);
            return result;
        }
        public static byte[] Slice(this byte[] array, int length)
        {
            Contract.Requires(array != null);

            if (length > array.Length)
            {
                throw new ArgumentOutOfRangeException("length", string.Format("length({0}) cannot be longer than Array.length({1})", length, array.Length));
            }
            return Slice(array, 0, length);
        }
}

Related Tutorials