Skip to content

Instantly share code, notes, and snippets.

@JRHeaton
Created March 23, 2012 22:53
Show Gist options
  • Save JRHeaton/2176057 to your computer and use it in GitHub Desktop.
Save JRHeaton/2176057 to your computer and use it in GitHub Desktop.
binary search for a friend
#include <stdio.h>
#include <stdlib.h>
typedef unsigned char byte;
byte *memfnd(char *buffer, size_t buflen, char *pattern, size_t patlen) {
if(!buffer || !pattern || !buflen || !patlen || patlen > buflen)
return NULL;
for(unsigned long i=0;i<buflen;++i) {
if(!memcmp(&buffer[i], pattern, patlen))
return (byte *)(buffer + i);
}
return NULL;
}
int main(int argc, const char **argv) {
char mem[5] = { 0xFF, 0xFA, 0xaa, 0xaa, 0xbc };
char pat[2] = { 0xfa, 0xaa };
printf("Offset: 0x%x\n", memfnd(mem, sizeof(mem), pat, sizeof(pat)) - (byte *)&mem);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment