字节模式查找(大海捞针) - 通配符/掩码



这是我第一次使用StackOverflow,很抱歉

,如果我含糊不清:P

我有这段代码,它在字节数组中搜索模式并返回它的位置。

public int FindPattern(byte[] Body, byte[] Pattern, int start = 0)
    {
        int foundIndex = -1;
        bool match = false;
        if (Body.Length > 0 && Pattern.Length > 0 && start <= Body.Length - Pattern.Length && Pattern.Length <= Body.Length)
            for (int index = start; index <= Body.Length - Pattern.Length; index += 4)
                if (Body[index] == Pattern[0])
                {
                    match = true;
                    for (int index2 = 1; index2 <= Pattern.Length - 1; index2++)
                    {
                        if (Body[index + index2] != Pattern[index2])
                        {
                            match = false;
                            break;
                        }
                    }
                    if (match)
                    {
                        foundIndex = index;
                        break;
                    }
                }
        return foundIndex;
    }

问题是我不知道我将如何包含字节掩码/通配符。

例如,如果我想找到以下字节模式:

0x5A, 0xC7, 0xAE, 0xB7, 0x2F

我将如何实现通配符搜索,因此如果我不知道字节数组中的某些字节或它们发生变化,例如,我将如何找到如下所示的模式:

0x5A, 0x??, 0xAE, 0xB7, 0x??

?? = 表示我不知道哪些字节会不时更改。

有人有解决方案吗? - 我环顾四周,但找不到太多信息

提前非常感谢!詹姆斯

修改代码以支持通配符非常简单。要使其在大量数据中搜索高效可能需要更复杂的算法,例如带有通配符的Boyer-Moore(抱歉,我没有代码)。

这是做前者的一种方法(在我的头顶上):

public int FindPattern(byte[] Body, byte[] Pattern, bool[] Wild, int start = 0)
    {
        int foundIndex = -1;
        bool match = false;
        if (Body.Length > 0 
            && Pattern.Length > 0 
            && start <= Body.Length - Pattern.Length && Pattern.Length <= Body.Length)
            for (int index = start; index <= Body.Length - Pattern.Length; index += 4)
                if (Wild[0] || (Body[index] == Pattern[0]))
                {
                    match = true;
                    for (int index2 = 1; index2 <= Pattern.Length - 1; index2++)
                    {
                        if (!Wild[index2] &&
                          (Body[index + index2] != Pattern[index2]))
                        {
                            match = false;
                            break;
                        }
                    }
                    if (match)
                    {
                        foundIndex = index;
                        break;
                    }
                }
        return foundIndex;
    }

这里的预期是你以完整的长度传入搜索模式,然后传递一个具有相同长度的通配符标志数组,所以你的示例

0x5A, 0x??, 0xAE, 0xB7, 0x??

将作为传入

0x5A, 0x00, 0xAE, 0xB7, 0x00, and then
false, true, false, false, true

最新更新