C# 字节模式查找(大海捞针)-通配符/掩码?
这是我第一次使用StackOverflow,如果我含糊不清,很抱歉:p 我有一段代码,它在字节数组中搜索一个模式并返回它的位置C# 字节模式查找(大海捞针)-通配符/掩码?,c#,arrays,byte,wildcard,mask,C#,Arrays,Byte,Wildcard,Mask,这是我第一次使用StackOverflow,如果我含糊不清,很抱歉:p 我有一段代码,它在字节数组中搜索一个模式并返回它的位置 public int FindPattern(byte[] Body, byte[] Pattern, int start = 0) { int foundIndex = -1; bool match = false; if (Body.Length > 0 && Pattern.Lengt
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, 0x??, 0xAE, 0xB7, 0x??
??=表示我不知道会不时更改的字节
有人有解决办法吗我已经到处找过了,但找不到太多的信息
非常感谢!,
James修改代码以支持通配符非常简单。要使其在大型数据体中高效搜索,可能需要更复杂的算法,比如带有通配符的Boyer Moore(对不起,我没有现成的代码) 这里有一种方法可以实现前一种(在我的脑海中): 将作为
0x5A, 0x00, 0xAE, 0xB7, 0x00, and then
false, true, false, false, true
您当前的方法签名无法获得通配符匹配。首先,您需要添加另一个参数来帮助您标记哪些模式是通配符,或者将字节模式更改为可以承载更多信息的数据类型(如自定义对象或字符串)。谢谢:)如果我转换为字符串,如何返回位置呢?如果您将
模式
转换为类似于示例中的字符串(使用0x???
),您可以将字符串片段转换回字节[],并使用逻辑中的其他片段跳过一些索引(跳过8位,因为整个字节都是通配符)?这仍然有点奇怪,因为无论在哪里调用此方法,都必须对字符串进行编码。转换为十六进制字符串…再次应用正则表达式?
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