[Solved] C# get part of array by array mask


I suggest finding the index of the first mask ocurrence:

private static int MaskIndex(byte[] source, byte[] mask) {
  if (mask.Length == 0)
    return 0; // or source.Length; or throw exception

  for (int i = 0; i < source.Length - mask.Length + 1; ++i) {
    bool found = true;

    for (int j = 0; j < mask.Length; ++j)
      if (source[i + j] != mask[j]) {
        found = false;

        break;
      }

    if (found)
      return i;
  }

  return source.Length;
}

Having this you can implement EscapeArray as

private byte[] EscapeArray(int startIndex, byte[] source, byte[] mask) {
  int n = MaskIndex(source, mask);

  if (startIndex > n)
    return new byte[0]; // or throw exception 

  return source.Skip(startIndex).Take(n - startIndex).ToArray();
}

Test:

byte[] source = new byte[] 
  { 97, 98, 99, 5, 15, 66, 77, 102, 0, 102, 0, 102, 0, 102, 0, 102, 0 };
byte[] mask = new byte[] 
  { 102, 0, 102, 0, 102, 0, 102, 0 };

// 97, 98, 99, 5, 15, 66, 77  
Console.WriteLine(string.Join(", ", EscapeArray(0, source, mask)));

// 97, 98, 99, 5, 15, 66, 77, 102, 0, 102, 0, 102, 0, 102, 0, 102, 0
Console.WriteLine(string.Join(", ", EscapeArray(0, source, new byte[] {123})));

solved C# get part of array by array mask