C# 如何在特定偏移量处找到 byte[] 模式

C# How do I find a byte[] pattern at a specific offset

我有这段代码 return 一个长字节模式。我如何添加它以便它在特定偏移量处搜索字节?

static public long 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;
                    }
                }
            }
            try
            {
                return positions[0];
            }
            catch (ArgumentOutOfRangeException)
            {
                MessageBox.Show("none found");
                return 0;
            }
            
        }

例如我想这样做: 我希望 SearchBytePattern 有一种从特定偏移量开始搜索的方法,例如:从偏移量 3(即偏移量 47)开始。

          byte[] needle = new byte[]
            {
                111, 111, 111
            };
            byte[] haystack = new byte[]
            {
               111, 111, 111, 47,  111, 111, 111, 47,  111, 111, 111, 47
            };

SearchBytePattern(needle, haystack)

您将需要第三个参数 offset

  • 开始搜索 offset
  • 如果 needlehaystackoffset 相比太长,您可以如下所示缩短搜索。
  • 不要复制数组,因为这会占用更多内存和时间,只需在数组内部搜索即可。
  • 这仍然是 O(m * n) 最坏情况下的时间复杂度。您可以使用 Knuth-Morris-Pratt 等更复杂的算法使其成为 O(m)(但它要复杂得多,对于小输入而言,开销不值得)。
        public static int Search(byte[] needle, byte[] haystack, int offset){
            if (haystack.Length - offset < needle.Length) {
                return -1;   // can't possibly find b/c needle is too long
            }
            for (int i = offset; i < haystack.Length; ++i) {
                for (int j = 0; j < needle.Length; ++j) {
                    if ((i + j) >= haystack.Length || needle[j] != haystack[i + j]) {
                        break;       // found non-match for attempt
                    }
                    if (j == needle.Length - 1) {
                        return i;    // matched all
                    }
                }
            }
            return -1;
        }

以上returns4为您的示例输入。