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

3
我将尝试将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);
}

1
“neither one works” 是什么意思?输出是什么? - Jon
3个回答

6

如果缓冲区足够大,你可以直接将数据写入其中:

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

之后,就没有什么要做了,因为你已经通过ref传递了buffer。个人认为这里使用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;

谢谢,Marc,但我遇到了这个错误:“error CS0103:当前上下文中不存在名称'encoding'”。 - Neil Weicher
@Neilw,这是来自你的问题... System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();(虽然公正地说,var encoding = Encoding.UTF8; 更容易)。 - Marc Gravell
糟糕!那个起作用了。只是拼写错误而已。谢谢! - Neil Weicher

1
这个将处理创建字节缓冲区:
byte[] bytes = Encoding.ASCII.GetBytes("Jabberwocky");

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

    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接