【问题标题】:Find bytes from an offset从偏移量中查找字节
【发布时间】:2017-08-10 06:12:22
【问题描述】:

所以我有这个:

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

这可以完美地获得具有特定字节集的偏移量,但现在我想做相反的事情,从特定偏移量中找到一组字节。 我该怎么做?

【问题讨论】:

  • 先寻找或读取偏移量?也许创建一个您想要做的示例输入和输出,有点不清楚您要做什么。
  • 对不起,我在这件事上是个大菜鸟,我找到了代码并为我想要的工作,我没有自己写。你能分享一个寻找或阅读的例子吗?也许以偏移量 0x763AFC 为例?我知道我很懒,但我已经尝试了很多我在 stackoverflow 上找到的方法,但都无法让它工作:/ 编辑:会像 get byte[] {0xXX, 0xYY, 0xZZ, 0xXY, 0xYX} 从偏移量 0x00763AFC
  • byte[] ReadBytes(Stream stream, long offset, long bytesCount) 这就是你需要的吗?从特定偏移量读取特定字节数?
  • 是的,这就是我需要的,但我在任何地方都看不到 ReadBytes 方法,它属于哪个类?

标签: c#


【解决方案1】:

试试这个例子:

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

更多关于SeekRead的细节

【讨论】:

  • @user1913644 不客气))如果正确,请标记此答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-01-16
  • 1970-01-01
  • 2018-10-12
  • 1970-01-01
  • 2015-03-12
  • 1970-01-01
相关资源
最近更新 更多