Thursday, September 08, 2005

Concatenating Byte Arrays

I needed to concatenate two byte arrays. My first thought was to create a destination buffer and then loop through each sources adding their elements to the destination one – something dirty ah!
Fortunately, before to write any line of code I found this beautiful class called Buffer in the System namespace.
So, how you can concatenate two byte arrays using it? Very simple:

byte[] b1 = new byte[]{1,2,3};
byte[] b2 = new byte[]{4,5,6,7,8,9};

byte[] c = new byte[b1.Length + b2.Length];

Buffer.BlockCopy(b1, 0, c, 0, b1.Length);
Buffer.BlockCopy(b2, 0, c, b1.Length, b2.Length);

That’s it. Thanks BCL folks!


Post a Comment

<< Home