开发者

Insert a byte array into another byte array at a specific position with c#

This might be a silly question, but have not found a simple answer yet...

I'm trying to insert a simple c# byte array into another byte array at a specific position. E.g. the existing bytes should be not be overridden, but just moved further back. Really just like you copy page some text block inside an existing text block.

  1. So far, I would create a new array with the length of both existing arrays.
  2. Copy the first array into 开发者_Python百科the new one until the position where the insert starts.
  3. Add the inserted array
  4. Add the rest of the existing array.

But I would assume this is something common and should be easier? Or am I wrong?


Use a List<byte> instead of a byte[]; it will provide the flexibility you are looking for...

List<byte> b1 = new List<byte>() { 45, 46, 47, 50, 51, 52 };
List<byte> b2 = new List<byte> { 48, 49 };
b1.InsertRange(3, b2);

Then if you need to go back to a byte[] for whatever reason you can call...

b1.ToArray();


But I would assume this is something common

If inserting a large chunk of data into the middle of another large chunk of data is something you do often then you might consider using a data structure designed to do that. An array is designed to be fixed in size and mutable in content. If your requirement includes "variable in size" then an array is the wrong data type for you. Consider instead a doubly linked list or a catenable deque.

and should be easier?

You've identified a trivial four-step algorithm that does what you want. It doesn't get much easier than that.


Look at Array.CopyTo.

Copies all the elements of the current one-dimensional Array to the specified one-dimensional Array starting at the specified destination Array index.


If performance is not important, consider:

var combined = first.Take(insertPosition)
                    .Concat(second)
                    .Concat(first.Skip(insertPosition))
                    .ToArray();

I suppose this is pretty much the four-step algo you've suggested, except the first step "comes at the end." However, do note that this is inefficient for a number of reasons, including a needlessly dynamic buffer and a redundant partial enumeration of the first array.

Otherwise, what you have suggested is perfectly fine.


If you could trade up your object for something a bit bigger you could look at things like a List which has an InsertRange method that does what you want (http://msdn.microsoft.com/en-us/library/884ee1fz.aspx). Of course using a different object may not be an option but its a suggestion for an easy way to do things. Also other objects might be more useful. Shop around... :)


An array, by definition, has a fixed size. You cannot insert or remove elements, just overwrite elements.

You should a list instead. Lists provide methods to insert or remove elements and subranges.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜