How to search in a BYTE array for a pattern?

后端 未结 4 1224
南旧
南旧 2021-01-04 09:02

I have a Byte array :

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

00FFFFFFFFFFFF0010AC4C4053433442341401030A2

4条回答
  •  一向
    一向 (楼主)
    2021-01-04 09:49

    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 
    #include 
    
    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
    }
    

提交回复
热议问题