Skip to content

Instantly share code, notes, and snippets.

@JKamsker
Created March 21, 2017 15:06
Show Gist options
  • Save JKamsker/822e92ee8cd510b49ea0e2940dbf3e8e to your computer and use it in GitHub Desktop.
Save JKamsker/822e92ee8cd510b49ea0e2940dbf3e8e to your computer and use it in GitHub Desktop.
Searches a bigger array of bytes for a tinyer array of bytes
public class Byte
{
/// <summary>
/// Gets the starting pointers in array of the given element
/// </summary>
/// <param name="array">Bigger element where is searched in</param>
/// <param name="element">Tiny pattern which has to be matched in <see cref="array"/></param>
/// <returns></returns>
public static List<int> GetOccurancePtrs(byte[] array, byte[] element)
{
var firstMatchPtrs = new List<int>();
var secondMatchPtrs = new List<int>();
int ihalp1 = array.Length - element.Length;
//Mark each and every position in the array where the first element matches
for (int i = 0; i < ihalp1; i++)
{
if (array[i] == element[0])
firstMatchPtrs.Add(i);
}
//Start the "Deep scan" by looking at the first pointer collection
for (int i = firstMatchPtrs.Count - 1; i >= 0; i--)
{
if (IsMatch(array, element, firstMatchPtrs[i]))
secondMatchPtrs.Add(firstMatchPtrs[i]);
}
return secondMatchPtrs;
}
private static bool IsMatch(byte[] array, byte[] element, int pointer)
{
//return false wenn pointer+element.lengh>ARRAY
if ((element.Length + pointer) > array.Length)
{
return false;
}
int ihalp2 = element.Length - 1;
for (int i = 0; i < ihalp2; i++)
{
if (array[i + pointer] != element[i])
return false;
}
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment