[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 (5)

  1. TOFguy says:

    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

  2. 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.  

  3. Shane says:

    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.

  4. 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.  

  5. TOFguy says:

    And yes, I did manage to have an error in a two line method. It should read:

    static void AppendByteArray(byte[] arrayA, byte[] arrayB)

    {

      arrayA.Resize(ref arrayA, arrayA.Length + arrayB.Length);

      Buffer.BlockCopy(arrayB, 0, arrayA, arrayA.Length – arrayB.Length, arrayB.Length);

    }