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

3 回答 3

5

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

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

在那之后,没有什么可做的,因为你已经昏倒bufferref。不过,就个人而言,我怀疑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;
于 2012-07-18T10:49:23.463 回答
1

这将处理创建字节缓冲区:

byte[] bytes = Encoding.ASCII.GetBytes("Jabberwocky");
于 2019-08-01T20:30:31.807 回答
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);
        }

    }
于 2018-02-05T12:15:46.537 回答