Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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?

like image 650
Remy Avatar asked Jan 06 '11 15:01

Remy


1 Answers

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();
like image 93
Aaron McIver Avatar answered Oct 01 '22 09:10

Aaron McIver