Eric
Eric

Reputation: 1268

How to Split a Byte[]

I need to split a byte[].

I have some data in an original byte[] that would look like:

byte[] m_B = new byte[] { 0x01, 0x02, 0x03, 0xc0, 0x04, 0x05, 0x06, 0xc0, 0x07, 0x08, 0x09 };

How would I split the byte[] everywhere "0xc0" exists?

Upvotes: 1

Views: 1618

Answers (1)

driis
driis

Reputation: 164291

Simply enumerate over your buffer and return a subset whenever you reach the byte to split on:

IEnumerable<byte[]> Split(byte splitByte, byte[] buffer) 
{
    List<byte> bytes = new List<byte>();
    foreach(byte b in buffer) 
    {
        if (b != splitByte)
            bytes.Add(b);
        else
        {
            yield return bytes.ToArray();
            bytes.Clear();
        }
    }
    yield return bytes.ToArray();
}

Upvotes: 6

Related Questions