在byte数组中定位已知byte[]
有时可能会想要在byte数组中定位已知数组的位置(恶狠狠看了一眼某仪器文档),以下代码完成此功能:
using System; using System.Collections.Generic; using System.Linq; namespace Hu { public class ByteMatch { /// <summary> /// 返回源序列中首个与指定匹配序列相同的子序列后的第一个字节在源序列中的索引,没有匹配返回-1 /// </summary> /// <param name="source">源序列</param> /// <param name="match">匹配序列</param> /// <returns></returns> public static int IndexAfter(IEnumerable<byte> source, IEnumerable<byte> match) { if (null == source || null == match) throw new ArgumentNullException(); if (false == source.Any() || false == match.Any()) throw new ArgumentException("源序列与匹配序列都须包含数据"); int sLen = source.Count(), mLen = match.Count(); if (sLen < mLen) throw new ArgumentException("匹配序列长度大于源序列长度"); bool matched = false; int idx = 0, offset = 0; var lst = source.ToList(); while (sLen - offset >= mLen) { idx = lst.IndexOf(match.ElementAt(0), offset); if (-1 == idx) break; if (sLen - idx >= mLen) { matched = true; for (int jdx = 1; jdx < mLen; jdx++) { if (source.ElementAt(idx + jdx) != match.ElementAt(jdx)) { matched = false; break; } } if (false == matched) offset = idx + 1; else break; } else break; } return matched ? (idx + mLen) : -1; } } }
--I love this guy.