Posted by: Cirilo Meggiolaro | 02/8/2009

Tip of the day #117 – Copying block of bytes between arrays with Buffer class

How can we copy a block of bytes between arrays? There are several ways to do that. The one we are going to check today is a static method called BlockCopy available under the System.Buffer class that perform the task of copy a block of bytes from a source array, replacing the bytes on a specified position in the destination array.

Method Signature

public static void BlockCopy(Array src, int srcOffset, Array dst, int dstOffset, int count);

The BlockCopy method accepts the following parameters:

  • src: Source array;
  • srcOffset: Start index from the source array;
  • dst: Destination array;
  • dstOffset: Index on the destination array where the copied bytes are being copied to;
  • count: Number of items to copy from the source array.

How to…

Since we now the method signature, the code is pretty straightforward:

/// Source array
short[] source = { 123, 146, 147, 160, 187, 192, 203, 207, 212, 215, 222 };

/// Destination array
short[] destination = { 7, 12, 16, 18, 26, 29, 42, 45, 49 };

/// Copies 6 items from the source array starting on the
/// index 5 to position 7 on the destination array.
Buffer.BlockCopy(source, 5, destination, 7, 6);

Output – Original Values

source:       7B 00 92 00 93 00 A0 00 BB 00 C0 00 CB 00 CF 00 D4 00 D7 00 DE 00
destination: 07 00 0C 00 10 00 12 00 1A 00 1D 00 2A 00 2D 00 31 00

Output – Modified Values

source:       7B 00 92 00 93 00 A0 00 BB 00 C0 00 CB 00 CF 00 D4 00 D7 00 DE 00
destination: 07 00 0C 00 10 00 12 00 A0 00 BB 00 C0 00 2D 00 31 00

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Categories

%d bloggers like this: