And he has one error, it cannot return a match with a length of 1
To fix this, start the inner loop from scratch:
public static bool SearchByteByByte(byte[] bytes, byte[] pattern) { bool found = false; int matchedBytes = 0; for (int i = 0; i < bytes.Length; i++) { if (pattern[0] == bytes[i] && bytes.Length - i >= pattern.Length) { for (int j = 0; j < pattern.Length; j++)
UPDATE: here is your search algorithm after flying and deleting local variables (they are not needed)
public static bool SearchByteByByte(byte[] bytes, byte[] pattern) { for (int i = 0; i < bytes.Length; i++) { if (bytes.Length - i < pattern.Length) return false; if (pattern[0] != bytes[i]) continue; for (int j = 0; j < pattern.Length; j++) { if (bytes[i + j] != pattern[j]) break; if (j == pattern.Length - 1) return true; } } return false; }
Sergey Berezovskiy
source share