C#将字符串复制到字节缓冲区 [英] C# copy string to byte buffer

查看:535
本文介绍了C#将字符串复制到字节缓冲区的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将Ascii字符串复制到字节数组,但是无法执行。

I am trying to copy an Ascii string to a byte array but am unable. How?

这是到目前为止我尝试过的两件事。都不起作用:

Here are the two things I have tried so far. Neither one works:

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


推荐答案

如果缓冲区足够大,您可以直接将其编写:

If the buffer is big enough, you can just write it directly:

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

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

However, you might need to check the length first; a test might be:

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 是一个错误的选择。除非您是从头开始复制,即

after that, there is nothing to do, since you are already passing buffer out by ref. Personally, I suspect that this ref is a bad choice, though. There is no need to BlockCopy here, unless you were copying from a scratch buffer, i.e.

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

这篇关于C#将字符串复制到字节缓冲区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆