【发布时间】:2016-01-22 06:38:48
【问题描述】:
我正在尝试在另一个字节数组 byte[] 中找到一个字节数组 byte[] 反向。
问题:如何在另一个字节数组中从头到尾搜索一个字节数组?
此链接是我正在制作的代码的参考 c# How to Continuously find a byte array inside a byte array?
编辑:我需要将此代码转换为在另一个反向字节数组中搜索字节数组。
indexPos = SearchBytes(input, find, indexPos);
Console.WriteLine("Found at " + indexPos);
indexPos += find.Length;
更新:当我点击按钮时,索引需要搜索如下:11, 6 1
我需要从头到尾搜索以下代码:
byte[] input = { 0, 1, 1, 1, 5, 6, 1, 1, 1, 7, 8, 1, 1, 1 };
byte[] find = { 1, 1, 1 };
int indexPos = 0;
private void button1_Click(object sender, EventArgs e)
{
indexPos = SearchBytes(input, find, indexPos);
Console.WriteLine("Found at " + indexPos);
indexPos += find.Length;
}
public int SearchBytes(byte[] haystack, byte[] needle, int start_index)
{
int len = needle.Length;
int limit = haystack.Length - len;
for (int i = start_index; i <= limit; i++)
{
int k = 0;
for (; k < len; k++)
{
if (needle[k] != haystack[i + k]) break;
}
if (k == len) return i;
}
return -1;
}
【问题讨论】:
-
澄清一下:例如,如果您有
haystack0, 1, 1, 1, 1, 5, 6, 7, 8并且您的needle是1,您会返回1或4作为索引位置吗?如果您的needle是1 5,您会返回索引4、5,还是返回-1(未找到)?最后,如果您的needle是5 1,您会返回4、5,还是返回-1(未找到)? -
@Ian 我需要它返回到 4 然后 3 依此类推。
-
我明白了,如果你有
haystack1 2 1 2 1 2会发生什么?如果你的针是1 2,你会返回 4 然后 2 然后 0 (注意我加粗了)?或者,您会从后面阅读2 1 2 1 2 1,因此最后一个将缺少2,您只会返回 4 然后 2? -
@Ian
haystack0 1 0 0 1 1 0needle 1我需要它来按以下顺序查找数字:5、4、1。然后下一个索引将是 -1 以重新启动。我只是想让代码反转它的搜索。我将不胜感激。谢谢。 -
我已经明白了,我正准备提供帮助,但我只是想知道你为什么在你的
needle中使用byte[]而不是byte,如果你只能有 1 个byte。这就是为什么我不断给出多个字节的例子为needle。那么,你的needle会不会只有 1 个byte?可以是多个字节吗?
标签: c# arrays search byte reverse