开发者

Array split by range?

I have an array, i don't know the length but i do know it will be >=4开发者_Python百科8bytes. The first 48bytes are the header and i need to split the header into two.

Whats the easiest way? I am hoping something as simple as header.split(32); would work ([0] is 32 bytes [1] being 16 assuming header is an array of 48bytes)

using .NET


Here i splitted array of ints into 2 arrays of 4 and the left elements:

var limit = 4;

int[] array = new int[] { 1, 2, 3, 4, 5, 6 };

int[][] res = array.Select((value, index) => new { index = index, value = value })
                   .GroupBy(i => i.index < limit)
                   .Select(g => g.Select(o => o.value).ToArray())
                   .ToArray();

UPD: remake with an extension:

class Program
{
    static void Main(string[] args)
    {
        int[] array = new int[] { 1, 2, 3, 4, 5, 6 };

        int[][] res = array.split(4);
    }
}

static class MyExtension
{
    public static int[][] split(this IEnumerable<int> array, int limit)
    {
        return array.Select((value, index) => new { index = index, value = value })
                    .GroupBy(i => i.index < limit)
                    .Select(g => g.Select(o => o.value).ToArray())
                    .ToArray();
    }
}


I decided to write something. It could be nicer like a extended function but it is good now.

    Byte[][] SplitArray(byte[] main, params int[] size)
    {
        List<Byte[]> ls = new List<byte[]>();
        int offset = 0;
        foreach (var v in size)
        {
            var b = new Byte[v];
            Array.Copy(main, offset, b, 0, v);
            ls.Add(b);
            offset += v;
        }
        {
            var b = new Byte[main.Length-offset];
            Array.Copy(main, offset, b, 0, b.Length);
            ls.Add(b);
        }
        return ls.ToArray();
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜