Is there any method in a C # search in a byte [] array of a particular sequence?

I have a file that I read like this: System.IO.File.ReadAllBytes(pathExe) . After reading, I need to find the position of the beginning of a specific sequence of 8 bytes (8 elements of the byte [] array). If there is a ready solution please indicate.

2 answers 2

There is always a solution in the form of hell Linq-one-line

 byte[] a = { 1, 2, 3, 4, 3, 2, 1 }; byte[] b = { 3, 4, 3, 2 }; int? n = Enumerable .Range(0, a.Length - b.Length + 1) .SkipWhile(x => b.Zip(a.Skip(x), (y, z) => y == z).Any(t => !t)) .Select(x => (int?)x) .FirstOrDefault(); Console.WriteLine(n); 

Returns the index of the first occurrence of array b in a or null if it is absent.

The same in classic imperative style:

 byte[] a = { 1, 2, 3, 4, 3, 2, 1 }; byte[] b = { 3, 4, 3, 2 }; int? n = null; for (int i = 0; i <= a.Length - b.Length; ++i) { bool f = true; for (int j = 0; j < b.Length; ++j) { f &= a[i + j] == b[j]; if (!f) break; } if (f) { n = i; break; } } Console.WriteLine(n); 
  • For some reason, so obsessive about me. - XXX
  • There is nothing to dwell on. Can you null be returned? - Andrei NOP
  • Probably looking for a long time, and not getting hung up. - XXX
  • I check everything with your arrays - OK. - XXX
  • with my arrays - thinks that minute already - XXX

Goodies from here - link

 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<int>(); for (int i = 0; i < 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 > (array.Length - position)) return false; for (int i = 0; i < 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 > 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); } }