2

Possible Duplicate:
C# arrays , Getting a sub-array from an existing array

Basically I have a byte[] that's going to be different every time, but it's going to be the same length.

Then, after that, I have more bytes with the data that I need.

If that doesn't make sense, this is basically what I mean.

"samebytesDataNeededIsHere"

So I need to get the data after "samebytes", and I'm not sure how to do it. I've searched and there's really nothing on this, besides byte patterns and that's not really what I need.

4

3 回答 3

7

怎么样

byte[] bytes = Encoding.UTF8.GetBytes("samebytesDataNeededIsHere");
byte[] bytesToUse = bytes.Skip(countOfBytesToSkip).ToArray();
于 2012-08-21T13:23:51.747 回答
2

你还没有说你在做什么,但是在很多byte[]处理代码中你使用缓冲区中的偏移量......所以,不是最初将此偏移量设置为0,而是将其设置为“相同的长度”字节”。

如果您正在包装MemoryStream,您可以Position在使用它之前将转发设置为该数字。

最后,您可以只复制所需的数据,也许使用Buffer.BlockCopy,指定起始偏移量。这将是我最不喜欢的选项,因为第二个缓冲区和块副本是多余的(我们已经拥有数据并且知道我们想要查看的位置)。

例子:

// invent some initial data
byte[] data = Encoding.ASCII.GetBytes("samebytesDataNeededIsHere");
int fixedOffset = 9; // length of samebytes

// as a segment
ArraySegment<byte> segment = new ArraySegment<byte>(data,
     fixedOffset, data.Length - fixedOffset);

// as a separate buffer
byte[] copy = new byte[data.Length - fixedOffset];
Buffer.BlockCopy(data, fixedOffset, copy, 0, copy.Length);

// as a stream
var ms = new MemoryStream(data, fixedOffset, data.Length - fixedOffset);

// or just directly
for(int i = fixedOffset ; i < data.Length ; i++) {
   // access data[i]
}
于 2012-08-21T13:21:47.537 回答
0

I think you are asking for how to retrieve a portion of a byte array from a constant start index. There are a variety of ways you can do this.

First, a simple loop:

// make sure you use the correct encoding
// see http://msdn.microsoft.com/en-us/library/ds4kkd55.aspx
byte[] bytes = Encoding.UTF8.GetBytes( "samebytesDataNeededIsHere" );

for( int i = startIndex; i < bytes.Length; i++ ){
  byte b = bytes[i]; // now do something with the value...
}

You could also use Array.CopyTo to copy a portion of one array into a new array. Of course, if you are dealing with an array of significant size, it would be better to not copy it but rather iterate through it or consume it as a stream (as @MarcGravell suggests).

于 2012-08-21T13:22:05.973 回答