How to do memcpy for Byte[]?

  • Thread starter Thread starter EOS
  • Start date Start date
E

EOS

I guess what I want to do is best explain via the codes here;

Byte[] byteA = new Byte[100000];
Byte[] byteB = new Byte[4];
....
....
....

Now I want to copy 4 bytes from certain portion of the byteA array.

In C/C++, this is what we do;

memcpy(byteB, byteA[X], 4);

Or

memcpy(byteB, byteA+X, 4);

But with C#, I had been stuck for a while with no luck....

Hope you understand what I wanted and could show me the way.

Thanks for your time. Sometime I wish Microsoft could create C# to be nearer
to C/C++. C# is still driving me headache...
 
You could try:

public void CopyPartialByte(byte[] from, ref byte[] to, int index)
{
for (int x = index; x < (to.Length + index); x++)
to[x - index] = from[x];
}

Then call it:
CopyPartialByte(byteA, ref byteB, index);

Like usual this is off the top of my head, might be an error in the loop
counting but you get the idea I hope.

Chris
 
balmerch said:
You could try:

public void CopyPartialByte(byte[] from, ref byte[] to, int index)
{
for (int x = index; x < (to.Length + index); x++)
to[x - index] = from[x];
}
The ref shouldn't be needed here. An array is a reference type

You can also use Buffer.BlockCopy() to copy from arrays, look it up in MSDN
for the specifics.
 
EOS said:
I guess what I want to do is best explain via the codes here;

Byte[] byteA = new Byte[100000];
Byte[] byteB = new Byte[4];

<snip>

See Buffer.BlockCopy, and Array.Copy.
 
Thanks! It is really easy to understand and to implement!

balmerch said:
You could try:

public void CopyPartialByte(byte[] from, ref byte[] to, int index)
{
for (int x = index; x < (to.Length + index); x++)
to[x - index] = from[x];
}

Then call it:
CopyPartialByte(byteA, ref byteB, index);

Like usual this is off the top of my head, might be an error in the loop
counting but you get the idea I hope.

Chris

EOS said:
I guess what I want to do is best explain via the codes here;

Byte[] byteA = new Byte[100000];
Byte[] byteB = new Byte[4];
....
....
....

Now I want to copy 4 bytes from certain portion of the byteA array.

In C/C++, this is what we do;

memcpy(byteB, byteA[X], 4);

Or

memcpy(byteB, byteA+X, 4);

But with C#, I had been stuck for a while with no luck....

Hope you understand what I wanted and could show me the way.

Thanks for your time. Sometime I wish Microsoft could create C# to be
nearer
to C/C++. C# is still driving me headache...
 
Back
Top