Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly search and parse an array using a sequence of elements as the target

I have a byte array that looks something like this:

byte[] exampleArray = new byte[] 
                      { 0x01, 0x13, 0x10, 0xe2, 0xb9, 0x13, 0x10, 0x75, 0x3a, 0x13 };

My end goal is to split this array into sub array's anytime I see the sequence { 0x13, 0x10 }. So my desired result on the example array would be:

{ 0x01 }
{ 0xe2, 0xb9 }
{ 0x75, 0x3a, 0x13 }

Ideally, I would also need to know that the final array, { 0x75, 0x3a, 0x13 }, did not end with the search sequence so that I could work with that as a special case.

Any thoughts on the best approach?

like image 442
Michael Mankus Avatar asked Nov 02 '22 23:11

Michael Mankus


1 Answers

List<byte[]> Split(byte[] bArray)
        {
            List<byte[]> result = new List<byte[]>();
            List<byte> tmp = new List<byte>();
            int i, n = bArray.Length;
            for (i = 0; i < n; i++)
            {
                if (bArray[i] == 0x13 && (i + 1 < n && bArray[i + 1] == 0x10))
                {
                    result.Add(tmp.ToArray());
                    tmp.Clear();
                    i++;
                }
                else
                    tmp.Add(bArray[i]);
            }
            if (tmp.Count > 0)
                result.Add(tmp.ToArray());
            return result;
        }

The last array can not end with sequence, any splited part does not contein separator. Only byte 0x13 can happen, so if this is importane for you, you can jast check last byte of last sub array.

like image 67
Viliam Avatar answered Nov 08 '22 04:11

Viliam