如何在另一个字节数组中找到一个字节数组

How to find a byte array inside another byte array

本文关键字:数组 字节数 字节 一个 另一个      更新时间:2023-10-16

我不能使用strstr, memchr因为数组可以包含任意数量的字符,是否有任何有效的方法来做到这一点?我必须找到所有的位置(索引)或指针。

c++中的小菜一碟:

#include <string>
const std::string needle = get_byte_sequence();
const std::string haystack = get_data();

std::size_t pos = haystack.find(needle);
// found if pos != std::string::npos

另一个选择是使用泛型算法:

#include <algorithm>
std::string::const_iterator it = std::search(data.begin(), data.end(), needle.begin(), needle.end());
if (it != data.end())
{
  // needle found at position std::distance(data.begin(), it);
}
else
{
  // needle not found
}

请记住c++ string对象可以包含任意数据。要从字节缓冲区创建字符串,将其大小传递给构造函数:

char buf[200];   // fill with your data; possibly full of zeros!
std::string s(buf, 200); // no problem

也许,你应该看看std::search ?(也有memem,但我不认为它是非常便携的)。

如果您希望遇到空字符,请使用标准函数memcmp(const void *, const void *, size_t)。

我正常工作

bool BinScanner::FindSequence(const unsigned char * pSeq, unsigned long ulSeqSize)
{
    const unsigned char* pFindRes = std::search(pCurr, pEnd, pSeq, pSeq+ulSeqSize);
    if (pFindRes != pEnd)
    {
        return true;
    }
}