首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >byte[]数组模式搜索

byte[]数组模式搜索
EN

Stack Overflow用户
提问于 2008-11-12 17:52:43
回答 23查看 106.8K关注 0票数 77

任何人都知道在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}
EN

回答 23

Stack Overflow用户

发布于 2016-07-28 09:29:46

这是我的建议,更简单,更快:

int Search(byte[] src, byte[] pattern)
{
    int maxFirstCharSlot = src.Length - pattern.Length + 1;
    for (int i = 0; i < maxFirstCharSlot; i++)
    {
        if (src[i] != pattern[0]) // compare only first byte
            continue;
        
        // found a match on first byte, now try to match rest of the pattern
        for (int j = pattern.Length - 1; j >= 1; j--) 
        {
           if (src[i + j] != pattern[j]) break;
           if (j == 1) return i;
        }
    }
    return -1;
}

这段代码背后的逻辑是这样的:首先它只搜索第一个字节(这是关键改进),当找到第一个字节时,我尝试匹配模式的其余部分

票数 18
EN

Stack Overflow用户

发布于 2008-11-12 13:21:26

使用高效的Boyer-Moore algorithm

它的设计目的是查找包含字符串的字符串,但您只需很少的想象力就可以将其映射到字节数组。

一般来说,最佳答案是:使用您喜欢的任何字符串搜索算法:)。

票数 12
EN

Stack Overflow用户

发布于 2008-11-12 10:55:04

我的解决方案是:

class Program
{
    public static void Main()
    {
        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};

        List<int> positions = SearchBytePattern(pattern, toBeSearched);

        foreach (var item in positions)
        {
            Console.WriteLine("Pattern matched at pos {0}", item);
        }

    }

    static public List<int> SearchBytePattern(byte[] pattern, byte[] bytes)
    {
        List<int> positions = new List<int>();
        int patternLength = pattern.Length;
        int totalLength = bytes.Length;
        byte firstMatchByte = pattern[0];
        for (int i = 0; i < totalLength; i++)
        {
            if (firstMatchByte == bytes[i] && totalLength - i >= patternLength)
            {
                byte[] match = new byte[patternLength];
                Array.Copy(bytes, i, match, 0, patternLength);
                if (match.SequenceEqual<byte>(pattern))
                {
                    positions.Add(i);
                    i += patternLength - 1;
                }
            }
        }
        return positions;
    }
}
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/283456

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档