Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在.NET中的较大集合中定位值序列(特别是字节)_.net_Byte_Sequence_Multibyte - Fatal编程技术网

如何在.NET中的较大集合中定位值序列(特别是字节)

如何在.NET中的较大集合中定位值序列(特别是字节),.net,byte,sequence,multibyte,.net,Byte,Sequence,Multibyte,我需要解析文件中的字节,这样我只能在确定某个字节序列后获取数据。例如,如果序列只是0xFF(一个字节),那么我可以在集合上使用LINQ: byte[] allBytes = new byte[] {0x00, 0xFF, 0x01}; var importantBytes = allBytes.SkipWhile(byte b => b != 0xFF); // importantBytes = {0xFF, 0x01} 但是,有没有一种优雅的方法来检测多字节序列(例如0xFF,0xFF

我需要解析文件中的字节,这样我只能在确定某个字节序列后获取数据。例如,如果序列只是0xFF(一个字节),那么我可以在集合上使用LINQ:

byte[] allBytes = new byte[] {0x00, 0xFF, 0x01};
var importantBytes = allBytes.SkipWhile(byte b => b != 0xFF);
// importantBytes = {0xFF, 0x01}

但是,有没有一种优雅的方法来检测多字节序列(例如0xFF,0xFF),特别是当它开始获得假阳性匹配时会回溯的多字节序列?

如果您将字节转换为字符串,您可以利用其中内置的无数搜索功能,即使您使用的字节实际上不是传统意义上的字符

我不知道任何内在的方式;和往常一样,您可以编写自己的扩展方法。下面是我脑海中的一个例子(可能有更有效的方法来实现它):


就像一点理论;这是一个常见的语言问题。您可以使用正则表达式引擎来检测它。谷歌首次成功搜索到“流上正则表达式”


您不必担心.NET对编码的假设以及会产生错误结果的假设吗?我相信,只要您搜索的是一个精确的字节序列,编码就不重要(只要源代码和搜索序列都是相同的编码)。您可以使用AscienceODing类来帮助来回转换。
public static IEnumerable<T> AfterSequence<T>(this IEnumerable<T> source,
    T[] sequence)
{
    bool sequenceFound = false;
    Queue<T> currentSequence = new Queue<T>(sequence.Length);
    foreach (T item in source)
    {
        if (sequenceFound)
        {
            yield return item;
        }
        else
        {
            currentSequence.Enqueue(item);

            if (currentSequence.Count < sequence.Length)
                continue;

            if (currentSequence.Count > sequence.Length)
                currentSequence.Dequeue();

            if (currentSequence.SequenceEqual(sequence))
                sequenceFound = true;
        }
    }
}
static void Main(string[] args)
{
    byte[] data = new byte[]
    {
        0x01, 0x02, 0x03, 0x04, 0x05,
        0xFF, 0xFE, 0xFD, 0xFC, 0xFB, 0xFA
    };
    byte[] sequence = new byte[] { 0x02, 0x03, 0x04, 0x05 };
    foreach (byte b in data.AfterSequence(sequence))
    {
        Console.WriteLine(b);
    }
    Console.ReadLine();
}