Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>May I suggest something that doesn't involve creating strings, copying arrays or unsafe code:</p> <pre><code>using System; using System.Collections.Generic; static class ByteArrayRocks { static readonly int [] Empty = new int [0]; public static int [] Locate (this byte [] self, byte [] candidate) { if (IsEmptyLocate (self, candidate)) return Empty; var list = new List&lt;int&gt; (); for (int i = 0; i &lt; self.Length; i++) { if (!IsMatch (self, i, candidate)) continue; list.Add (i); } return list.Count == 0 ? Empty : list.ToArray (); } static bool IsMatch (byte [] array, int position, byte [] candidate) { if (candidate.Length &gt; (array.Length - position)) return false; for (int i = 0; i &lt; candidate.Length; i++) if (array [position + i] != candidate [i]) return false; return true; } static bool IsEmptyLocate (byte [] array, byte [] candidate) { return array == null || candidate == null || array.Length == 0 || candidate.Length == 0 || candidate.Length &gt; array.Length; } static void Main () { var data = new byte [] { 23, 36, 43, 76, 125, 56, 34, 234, 12, 3, 5, 76, 8, 0, 6, 125, 234, 56, 211, 122, 22, 4, 7, 89, 76, 64, 12, 3, 5, 76, 8, 0, 6, 125 }; var pattern = new byte [] { 12, 3, 5, 76, 8, 0, 6, 125 }; foreach (var position in data.Locate (pattern)) Console.WriteLine (position); } } </code></pre> <hr> <p><strong>Edit (by IAbstract)</strong> - <em>moving contents of <a href="https://stackoverflow.com/a/283815/210709">post</a> here since it is not an answer</em></p> <p>Out of curiosity, I've created a small benchmark with the different answers.</p> <p>Here are the results for a million iterations:</p> <pre><code>solution [Locate]: 00:00:00.7714027 solution [FindAll]: 00:00:03.5404399 solution [SearchBytePattern]: 00:00:01.1105190 solution [MatchBytePattern]: 00:00:03.0658212 </code></pre> <hr>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload