kampi kampi - 3 months ago 11
C Question

How to search in a BYTE array for a pattern?

I have a Byte array :

BYTE Buffer[20000];
this array contains the following data:


00FFFFFFFFFFFF0010AC4C4053433442341401030A2F1E78EEEE95A3544C99260F5054A54B00714F8180B3000101010101010101010121399030621A274068B03600DA281100001C000000FF003457314D44304353423443530A000000FC0044454C4C2050323231300A2020000000FD00384B1E5310000A20202020202000FA


My question is how can i search this array for a pattern like "
000000FC
"? I don't really think it is important, but i need the index where i can find my pattern too. Could someone provide an example for this, because i don't really understand this :(

Answer

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
}
Comments