简体   繁体   中英

Find bytes from an offset

So I have this:

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;
}

Which works perfectly to get an offset that has a specific set of bytes, but now I want to do the inverse, find a set of bytes from a specific offset. How can I do that?

Try this example:

long offset = 100L; // Offset
int bytesCount = 20; // Number of bytes to read
byte[] buffer = new byte[bytesCount];

stream.Seek( offset, SeekOrigin.Begin ); // Set offset from Begin of a stream
stream.Read( buffer, 0, bytesCount ); // Read bytesCount from previous set offset

More detail about Seek and Read

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM