3

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);
}
1
  • 1
    What does "neither one works" mean? What's the output? Commented Jul 18, 2012 at 10:48

3 Answers 3

6

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, Marc, but I get this error: "error CS0103: The name 'encoding' does not exist in the current context"
@Neilw that came from your question... System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding(); (although to be fair, var encoding = Encoding.UTF8; would be easier)
Doh! That woked. Just a misspelling. Thanks!
1

This one will deal with creating the byte buffer:

byte[] bytes = Encoding.ASCII.GetBytes("Jabberwocky");

Comments

0

Maybe somebody needs standard c code function like strcpy convert to c#

    void strcpy(ref byte[] ar,int startpoint,string str)
    {
        try
        {
            int position = startpoint;
            byte[] tempb = Encoding.ASCII.GetBytes(str);
            for (int i = 0; i < tempb.Length; i++)
            {
                ar[position] = tempb[i];
                position++;
            }
        }
        catch(Exception ex)
        {
            System.Diagnostics.Debug.WriteLine("ER: "+ex.Message);
        }

    }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.