C#将字符串复制到字节缓冲区

时间:2012-07-18 10:44:25

标签: c# string bytearray

我真的感觉像个公爵夫人。我已经阅读了一些关于如何做到这一点的文章,但我似乎无法使它工作。我试图将Ascii字符串复制到字节数组。以下是我迄今为止尝试过的两件事。两者都不起作用:

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);
}

有人可以告诉我该怎么做吗?感谢。

3 个答案:

答案 0 :(得分:3)

如果缓冲区足够大,你可以直接写它:

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

但是,您可能需要先检查长度;测试可能是:

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;
}

之后,无所事事,因为您已经buffer传递了ref。就个人而言,我怀疑这个ref是一个糟糕的选择。这里不需要BlockCopy,除非您从暂存缓冲区复制,即

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

答案 1 :(得分:0)

也许有人需要标准的c代码函数,比如strcpy转换为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);
        }

    }

答案 2 :(得分:0)

这将涉及创建字节缓冲区:

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