C# copy string to byte buffer

13,639

Solution 1

If the buffer is big enough, you can just write it directly:

encoding.GetBytes(mystring, 0, mystring.Length, buffer, 0)

However, you might need to check the length first; a test might be:

if(encoding.GetMaxByteCount(mystring.length) <= buflen // cheapest first
   || encoding.GetByteCount(mystring) <= buflen)
{
    return encoding.GetBytes(mystring, 0, mystring.Length, buffer, 0)
}
else
{
    buffer = encoding.GetBytes(mystring);
    return buffer.Length;
}

after that, there is nothing to do, since you are already passing buffer out by ref. Personally, I suspect that this ref is a bad choice, though. There is no need to BlockCopy here, unless you were copying from a scratch buffer, i.e.

var tmp = encoding.GetBytes(mystring);
// copy as much as we can from tmp to buffer
Buffer.BlockCopy(tmp, 0, buffer, 0, buflen);
return buflen;

Solution 2

This one will deal with creating the byte buffer:

byte[] bytes = Encoding.ASCII.GetBytes("Jabberwocky");
Share:
13,639
Neil Weicher
Author by

Neil Weicher

Founder and CTO of NetLib Security Inc www.netlibsecurity.com Providing data encryption and key management for over twenty years.

Updated on June 23, 2022

Comments

  • Neil Weicher
    Neil Weicher almost 2 years

    I am trying to copy an Ascii string to a byte array but am unable. How?


    Here are the two things I have tried so far. Neither one works:

    public int GetString (ref byte[] buffer, int buflen)
    {
        string mystring = "hello world";
    
        // I have tried this:
        System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();
        buffer = encoding.GetBytes(mystring);
    
        // and tried this:
        System.Buffer.BlockCopy(mystring.ToCharArray(), 0, buffer, 0, buflen);  
       return (buflen);
    }