栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

在Stream中找到给定字节序列开始的位置的最佳方法

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

在Stream中找到给定字节序列开始的位置的最佳方法

我已经找到了解决方案。

我做了一些基准测试与是一个ASCII文件

3.050 KB
38803 lines
。与搜索
byte
array
22bytes
在文件的最后一行,我得到了在有关结果
2.28
秒(在慢/旧机)。

public static long FindPosition(Stream stream, byte[] byteSequence){    if (byteSequence.Length > stream.Length)        return -1;    byte[] buffer = new byte[byteSequence.Length];    using (BufferedStream bufStream = new BufferedStream(stream, byteSequence.Length))    {        int i;        while ((i = bufStream.Read(buffer, 0, byteSequence.Length)) == byteSequence.Length)        { if (byteSequence.SequenceEqual(buffer))     return bufStream.Position - byteSequence.Length; else     bufStream.Position -= byteSequence.Length - PadLeftSequence(buffer, byteSequence);        }    }    return -1;}private static int PadLeftSequence(byte[] bytes, byte[] seqBytes){    int i = 1;    while (i < bytes.Length)    {        int n = bytes.Length - i;        byte[] aux1 = new byte[n];        byte[] aux2 = new byte[n];        Array.Copy(bytes, i, aux1, 0, n);        Array.Copy(seqBytes, aux2, n);        if (aux1.SequenceEqual(aux2)) return i;        i++;    }    return i;}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/637465.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号