gpt4 book ai didi

c# - byte[] 数组模式搜索

转载 作者:IT王子 更新时间:2023-10-29 03:43:04 27 4
gpt4 key购买 nike

任何人都知道在 byte[] 数组中搜索/匹配字节模式然后返回位置的好而有效的方法。

例如

byte[] pattern = new byte[] {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}

最佳答案

我可以建议一些不涉及创建字符串、复制数组或不安全代码的东西吗:

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) - 移动 post 的内容在这里,因为它不是答案

出于好奇,我创建了一个带有不同答案的小基准。

这是一百万次迭代的结果:

solution [Locate]:            00:00:00.7714027
solution [FindAll]: 00:00:03.5404399
solution [SearchBytePattern]: 00:00:01.1105190
solution [MatchBytePattern]: 00:00:03.0658212

关于c# - byte[] 数组模式搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/283456/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com