关于我们

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻公共列表

在byte数组中定位已知byte[]

发布时间:2020-04-02 00:00:00

有时可能会想要在byte数组中定位已知数组的位置(恶狠狠看了一眼某仪器文档),以下代码完成此功能:

using System;using System.Collections.Generic;using System.Linq;namespace Hu
{public class ByteMatch
    {/// /// 返回源序列中首个与指定匹配序列相同的子序列后的第一个字节在源序列中的索引,没有匹配返回-1/// /// 源序列/// 匹配序列/// 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;elsebreak;
                }elsebreak;
            }return matched ? (idx + mLen) : -1;
        }
    }
}
View Code

 


/template/Home/Zkeys/PC/Static