【问题标题】:C# copy string to byte bufferC# 将字符串复制到字节缓冲区
【发布时间】:2012-07-17 09:09:19
【问题描述】:

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

【问题讨论】:

  • “两者都不起作用”是什么意思?输出是什么?

标签: c# arrays string


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    也许有人需要标准的 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);
            }
    
        }
    

    【讨论】:

      【解决方案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;
      

      【讨论】:

      • 谢谢,Marc,但我收到此错误:“错误 CS0103:当前上下文中不存在名称‘编码’”
      • @Neilw 来自您的问题...System.Text.UTF8Encoding encoding = new System.Text.UTF8Encoding();(虽然公平地说,var encoding = Encoding.UTF8; 会更容易)
      • 噢!就这样醒了。只是拼写错误。谢谢!
      猜你喜欢
      • 2015-10-29
      • 1970-01-01
      • 1970-01-01
      • 2012-08-15
      • 2010-09-27
      • 2018-11-24
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多