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

2023-12-25

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

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

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 out by ref。就我个人而言,我suspect那个这个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;
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C# 将字符串复制到字节缓冲区 的相关文章

随机推荐