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);
}
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;
This one will deal with creating the byte buffer:
byte[] bytes = Encoding.ASCII.GetBytes("Jabberwocky");
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With