harik
harik

Reputation: 583

Updating multi-dimension byte array in C#

I have a two dimension byte array and want to update/copy each array of data from one dimension arrays.

var multi = new byte[5, 200];

var single0 = new byte[200]; // initialized to some data

var single1 = new byte[200]; // initialized to some data

var single2 = new byte[200]; // initialized to some data

var single3 = new byte[200]; // initialized to some data

var single4 = new byte[200]; // initialized to some data


Buffer.BlockCopy(single0, 0, multi, 0, single0.Count());

Buffer.BlockCopy(single1, 0, multi, 1, single1.Count());

Buffer.BlockCopy(single2, 0, multi, 2, single2.Count());

Buffer.BlockCopy(single3, 0, multi, 3, single3.Count());

Buffer.BlockCopy(single4, 0, multi, 4, single4.Count());

But this is not working as expected. Only first row gets updated.

Any help is appreciated. Thanks.

Upvotes: 2

Views: 973

Answers (1)

Jon Skeet
Jon Skeet

Reputation: 1500815

Your fourth argument is wrong. It's meant to be the offset within the target array. That target array is effectively 5 "blocks" of 200 bytes back-to-back. So you'd want:

int stride = single0.Length; // Or multi.GetLength(1)
Buffer.BlockCopy(single0, 0, multi, stride * 0, stride);
Buffer.BlockCopy(single1, 0, multi, stride * 1, stride);
Buffer.BlockCopy(single2, 0, multi, stride * 2, stride);
Buffer.BlockCopy(single3, 0, multi, stride * 3, stride);
Buffer.BlockCopy(single4, 0, multi, stride * 4, stride);

Upvotes: 5

Related Questions