如何拆分字节[]

时间:2011-11-07 19:14:33

标签: c# .net

我需要拆分一个字节[]。

我在原始byte []中有一些看起来像这样的数据:

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

如何在“0xc0”存在的地方拆分字节[]?

1 个答案:

答案 0 :(得分:6)

只需枚举缓冲区并在到达要拆分的字节时返回子集:

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();
}