byte []数组模式搜索 [英] byte[] array pattern search
问题描述
任何人都知道来搜索字节模式/匹配在byte []数组,然后返回的位置的良好和有效的方式。
Anyone know a good and effective way to search/match for a byte pattern in an byte[] array and then return the positions.
例如
字节[] =模式新的字节[] { 12,3,5,76,8,0,6,125 };
byte[] pattern = new byte[] {12,3,5,76,8,0,6,125};
字节[] = toBeSearched新的字节[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125}
byte[] toBeSearched = new byte[] {23,36,43,76,125,56,34,234,12,3,5,76,8,0,6,125,234,56,211,122,22,4,7,89,76,64,12,3,5,76,8,0,6,125}
推荐答案
我建议的东西,不涉及创建字符串数组复制或不安全code:
May I suggest something that doesn't involve creating strings, copying arrays or unsafe code:
using System;
using System.Collections.Generic;
static class ByteArrayRocks {
static readonly int [] Empty = new int [0];
public static int [] Locate (this byte [] self, byte [] candidate)
{
if (IsEmptyLocate (self, candidate))
return Empty;
var list = new List<int> ();
for (int i = 0; i < self.Length; i++) {
if (!IsMatch (self, i, candidate))
continue;
list.Add (i);
}
return list.Count == 0 ? Empty : list.ToArray ();
}
static bool IsMatch (byte [] array, int position, byte [] candidate)
{
if (candidate.Length > (array.Length - position))
return false;
for (int i = 0; i < candidate.Length; i++)
if (array [position + i] != candidate [i])
return false;
return true;
}
static bool IsEmptyLocate (byte [] array, byte [] candidate)
{
return array == null
|| candidate == null
|| array.Length == 0
|| candidate.Length == 0
|| candidate.Length > array.Length;
}
static void Main ()
{
var data = new byte [] { 23, 36, 43, 76, 125, 56, 34, 234, 12, 3, 5, 76, 8, 0, 6, 125, 234, 56, 211, 122, 22, 4, 7, 89, 76, 64, 12, 3, 5, 76, 8, 0, 6, 125 };
var pattern = new byte [] { 12, 3, 5, 76, 8, 0, 6, 125 };
foreach (var position in data.Locate (pattern))
Console.WriteLine (position);
}
}
修改(由IAbstract) - 搬到这里的帖子内容,因为它是不是答案的
Edit (by IAbstract) - moving contents of post here since it is not an answer
出于好奇,我创建了一个小的基准与不同的答案。
Out of curiosity, I've created a small benchmark with the different answers.
下面是一百万次迭代的结果:
Here are the results for a million iterations:
solution [Locate]: 00:00:00.7714027
solution [FindAll]: 00:00:03.5404399
solution [SearchBytePattern]: 00:00:01.1105190
solution [MatchBytePattern]: 00:00:03.0658212
这篇关于byte []数组模式搜索的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!