3

I have two byte arrays - array1 and array2 . My aim is to copy the bytes from 1st array to second with respect to the start index of each array and fill the non filled bytes with a specific byte.

byte[] array1 = new byte[5]
The data is as follows: 11,22,00,33,44; 

byte[] array2 = new byte[10];     

I need to copy the bytes from array1 to array2. The data needs to be copied from position 3 in array2 and fill the rest of the empty positions with value ff. ie my result in array2 would be {ff,ff,ff,11,22,00,33,44,ff,ff}

Any help would be appreciable.

Thanks in advance!

4
  • There is an Array.Copy overload that lets you control the start index of the copy action. So create an array, initialise all elements to ff then copy on top of it (this would make for the simplest code). And here you are :-) Commented Nov 12, 2014 at 12:53
  • You show a small array in your example, so I would think that efficiency is NOT an issue. If so, then the solution given by Thomas below will be fine. However if you are using very large arrays and you need it to be as fast as possible, then the setting of the elements to zero can be further optimised. Commented Nov 12, 2014 at 13:06
  • @MatthewWatson : Yes I am dealing with large arrays.Can you please explain how can it be optimized? Commented Nov 12, 2014 at 13:11
  • @Ani_1317 The optimisation is just to set to 0xFF the parts of the array that are not affected by the Array.Copy(). This is just needs a simple calculation of the offsets involved. Commented Nov 12, 2014 at 13:49

1 Answer 1

6
// Init array2 to 0xff
for (int i = 0; i < array2.Length; i++)
    array2[i] = 0xff;

// Copy
Array.Copy(array1, 0, array2, 3, array2.Length);
Sign up to request clarification or add additional context in comments.

3 Comments

But Array.copy affects the performance when compared to buffer.blockCopy right?
@Ani_1317, perhaps... you need to benchmark it to be sure.
@Ani_1317 I just tested this (release build) and there is no difference in speed. Array.Copy() is highly optimised.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.