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.

Community
  • 1
  • 1
Banksy
  • 51
  • 2
  • 6

3 Answers3

8

How about

byte[] bytes = Encoding.UTF8.GetBytes("samebytesDataNeededIsHere");
byte[] bytesToUse = bytes.Skip(countOfBytesToSkip).ToArray();
ghostJago
  • 3,381
  • 5
  • 36
  • 51
Justin Harvey
  • 14,446
  • 2
  • 27
  • 30
2

You haven't said what you are doing with this, but in a lot of byte[] processing code you work with an offset into the buffer... so, instead of initially setting this offset to 0, you would set it to the length of "same bytes".

If you are wrapping in MemoryStream, you could just set the Position forward to that number before working with it.

Finally, you could just copy the desired data out, perhaps using Buffer.BlockCopy, specifying the start offset. This would be my least preferred option, as the second buffer and block copy is redundant (we already have the data and know where we want to look).

Examples:

// 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]
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
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).

Tim M.
  • 53,671
  • 14
  • 120
  • 163