tags:

views:

60

answers:

2

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

+2  A: 

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();
    }
}
zerkms
Looks complex. Still, +1.
acidzombie24
@acidzombie24: hide it into `split` `IEnumerable` extension ;-) (see **UPD**)
zerkms
A: 

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();
    }
acidzombie24
We know in advanced header is going to split two halves, so why can’t use a 2D array instead of a list
Upul
In this case you can see the function splits it according to how many size params are passed in so SplitArray can have 0-n splits. Even though i can do size.Length or .Count i am still lazy and like to use list. Also i have no index in a foreach loop which is pushing my lazyness to use add()
acidzombie24