Split byte array to two dimensional byte array - CSharp System

CSharp examples for System:Byte Array

Description

Split byte array to two dimensional byte array

Demo Code

// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
using System.Collections.Generic;
using System;/*from ww  w  . j av a2 s .c  om*/

public class Main{
        internal static byte[][] Split(this byte[] source, int limit)
        {
            if (source.Length <= limit)
            {
                throw new ArgumentOutOfRangeException("limit");
            }

            var chunkCount = ((source.Length - 1) / limit) + 1;
            var chunks = new byte[chunkCount][];

            var lastChunkIndex = chunkCount - 1;
            var currentPosition = 0;
            for (int i = 0; i < lastChunkIndex; i++)
            {
                var chunk = new byte[limit];
                Array.Copy(source, currentPosition, chunk, 0, limit);
                chunks[i] = chunk;
                currentPosition += limit;
            }

            var lastChunkLength = Math.Min(limit, source.Length - currentPosition);
            var lastChunk = new byte[lastChunkLength];
            Array.Copy(source, currentPosition, lastChunk, 0, lastChunkLength);
            chunks[lastChunkIndex] = lastChunk;

            return chunks;
        }
}

Related Tutorials