Partager via


[C#] Two Easy Tricks to Play with Byte Array Using Buffer.BlockCopy

A lot of times when I have to feed some APIs with byte array(byte[]), I got myself confused during converting what I have in hand(usually a string or even, a string array) to what I want it to be. There are certainly a lot of ways you could conduct this convention, and most of them works fairly well in terms of performance and space consumption. While putting these two criteria's aside, here're two simple and self-explained helper methods that will do the trick:

 static byte[] ConvertToBytes(string inputString)
 {
 byte[] outputBytes = new byte[inputString.Length * sizeof(char)];
 Buffer.BlockCopy(inputString.ToCharArray(), 0, outputBytes, 0, outputBytes.Length);
 return outputBytes;
 }

In some other cases when you want to concatenate two byte arrays, while you don't want to bother doing the convention between strings. Here's a easy way of doing it, which also employs Buffer.BlockCopy. Note that it appends the Byte[] arrayB to the end of Byte[] arrayA:

 static byte[] AppendTwoByteArrays(byte[] arrayA, byte[] arrayB)
 {
 byte[] outputBytes = new byte[arrayA.Length + arrayB.Length];
 Buffer.BlockCopy(arrayA, 0, outputBytes, 0, arrayA.Length);
 Buffer.BlockCopy(arrayB, 0, outputBytes, arrayA.Length, arrayB.Length);
 return outputBytes;
 }

Comments

  • Anonymous
    July 07, 2012
    Good article - thanks. Perhaps an addition that might be useful is: static void AppendByteArray(byte[] arrayA, byte[] arrayB) {    arrayA.Resize(ref arrayA, arrayA.Length + arrayB.Length);    Buffer.BlockCopy(arrayB, 0, arrayA, arrayA.Length, arrayB.Length); } (Apologies/warning, on iPad so have not run code!) Mark

  • Anonymous
    July 08, 2012
    Thanks Mark, that certianly works too. (and does a better job on space consuming) One just need to choose which one to use by whether he wants to keep the old array(arrayA) unmodified.  

  • Anonymous
    July 10, 2012
    Why not:    static byte[] ConvertToBytes(string inputString)    {        return System.Text.Encoding.Unicode.GetBytes(inputString);    } I am learning, so maybe there is a reason. I do not see any performance hit.

  • Anonymous
    July 11, 2012
    Shane, the problem is there are many other encoding mechs besides unicode, and you need to make sure you are using the right one, depending on what your input is. Except that, what you did works perfectly fine.  

  • Anonymous
    July 12, 2012
    The comment has been removed