Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy byte array to another byte array in C#

Tags:

arrays

c#

There are two byte arrays which are populated with different values.

byte[] Array1 = new byte[5]; byte[] Array2 = new byte[5]; 

Then, I need Array1 to get exactly the same values as Array2.

By typing Array1 = Array2 I would just set references, this would not copy the values.

What might be the solution?

EDIT:

All answers are good and all solutions work. The code from the first solution looks visually more descriptive for my particular case.

Array1 = Array2.ToArray();

and

Array1.CopyTo(Array2, 0);

as well as

Buffer.BlockCopy(Array2, 0, Array1, 0, 5);

like image 363
acoder Avatar asked Jan 17 '16 00:01

acoder


People also ask

How do you copy byte array?

copyOf(byte[] original, int newLength) method copies the specified array, truncating or padding with zeros (if necessary) so the copy has the specified length. For all indices that are valid in both the original array and the copy, the two arrays will contain identical values.

Does memcpy copy in bytes?

Threadsafe: Yes. The memcpy() function copies count bytes of src to dest . The behavior is undefined if copying takes place between objects that overlap. The memmove() function allows copying between objects that might overlap.

Does memcpy work with arrays?

Memcpy copies data bytes by byte from the source array to the destination array. This copying of data is threadsafe. The process of copying data can fail if the given size is not accurate for the destination array.

How do you convert a byte array into a string?

There are two ways to convert byte array to String: By using String class constructor. By using UTF-8 encoding.


2 Answers

One solution courtesy of Linq...

Array1 = Array2.ToArray(); 

EDIT: you do not need to allocate space for Array1 before using this Linq call. The allocation for Array1 is done within ToArray(). More complete example below

byte[] Array2 = new byte[5]; // set values for Array2 byte[] Array1 = Array2.ToArray(); 
like image 121
Frank Bryce Avatar answered Sep 30 '22 01:09

Frank Bryce


Array1.CopyTo(Array2, 0); 

MSDN

like image 45
Qwertiy Avatar answered Sep 30 '22 01:09

Qwertiy