简体   繁体   中英

Array split by range?

I have an array, i don't know the length but i do know it will be >=48bytes. 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();
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM