How to search in a BYTE array for a pattern?
You want something like memmem
(that code is licensed with the GPL).
However, it should not be difficult to roll your own. Like in memmem
's implementation, you need a loop that uses memchr
to find the first character of your needle in the haystack, and memcmp
to test each hit and see if all of your needle is there.
Since you're in C++, do it the C++ way:
char a[] = { 0, 0, 0, 0xFC };
char Buffer[20000] = ...
std::string needle(a, a + 4);
std::string haystack(Buffer, Buffer + 20000); // or "+ sizeof Buffer"
std::size_t n = haystack.find(needle);
if (n == std::string::npos)
{
// not found
}
else
{
// position is n
}
You can also use an algorithm to search the array directly:
#include <algorithm>
#include <iterator>
auto it = std::search(
std::begin(Buffer), std::end(Buffer),
std::begin(a), std::end(a));
if (it == std::end(Buffer))
{
// not found
}
else
{
// subrange found at std::distance(std::begin(Buffer), it)
}
Or, in C++17, you can use a string view:
std::string_view sv(std::begin(Buffer), std::end(Buffer));
if (std::size_t n = sv.find(needle); n != sv.npos)
{
// found at position n
}
else
{
// not found
}
Try this, just needed it:
// Returns a pointer to the first byte of needle inside haystack,
static uint8_t* bytes_find(uint8_t* haystack, size_t haystackLen, uint8_t* needle, size_t needleLen) {
if (needleLen > haystackLen) {
return false;
}
uint8_t* match = memchr(haystack, needle[0], haystackLen);
if (match != NULL) {
size_t remaining = haystackLen - ((uint8_t*)match - haystack);
if (needleLen <= remaining) {
if (memcmp(match, needle, needleLen) == 0) {
return match;
}
}
}
return NULL;
}