Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# copy string to byte buffer

Tags:

arrays

string

c#

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);
}
like image 834
Neil Weicher Avatar asked Jan 01 '26 01:01

Neil Weicher


2 Answers

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;
like image 123
Marc Gravell Avatar answered Jan 03 '26 01:01

Marc Gravell


This one will deal with creating the byte buffer:

byte[] bytes = Encoding.ASCII.GetBytes("Jabberwocky");
like image 25
ΩmegaMan Avatar answered Jan 03 '26 02:01

ΩmegaMan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!