3

Supposing I have a byte array of size 4096, what's an efficient way to get the start position of a chunk of say... 5 bytes that matches a pattern?

For e.g., I would like to get the start position of the 1st possible match of the byte array

var match = new byte[] { 0x03, 0x04, 0x05, 0x06, 0x07 };

So if the above chunk is found within my byte array, it will return me the position of the 1st byte (0x03)

Soner Gönül
  • 97,193
  • 102
  • 206
  • 364
Null Reference
  • 11,260
  • 40
  • 107
  • 184
  • if your search pattern in {0x03, 0x05}, what would you expect to see like a result? – Tigran Jul 01 '13 at 08:43
  • This might help you: http://stackoverflow.com/questions/3028768/net-regular-expressions-on-bytes-instead-of-chars – Regenschein Jul 01 '13 at 08:43
  • 2
    Also see this answer which uses the Boyer-Moore pattern matching algorithm (which is probably what I'd go for): http://stackoverflow.com/a/9890164/106159 – Matthew Watson Jul 01 '13 at 08:48
  • +1 for the `Boyer-Moore's` pattern, it's quite efficient as it skips bytes that would not match rather than brute-forcing through all the bytes. – keyboardP Jul 01 '13 at 08:50

1 Answers1

3

You can use Linq:

public static int IndexOfArray<T>(T[] source, T[] search)
{

    var result = Enumerable.Range(0, source.Length - search.Length)
                           .Select(i => new
                           {
                               Index = i,
                               Found = source.Skip(i)
                                  .Take(search.Length)
                                  .SequenceEqual(search)
                           })
                           .FirstOrDefault(e => e.Found);
    return result == null ? -1 : result.Index;
}        
Ahmed KRAIEM
  • 10,267
  • 4
  • 30
  • 33