欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-05-28 23:10:23
有时可能会想要在byte数组中定位已知数组的位置(恶狠狠看了一眼某仪器文档),以下代码完成此功能: using System; using System.Collections.Generic; using System.Linq; namespace Hu { public class ByteM ......

有时可能会想要在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;
        }
    }
}