How to get a null terminated string from a C# string?

前提是你 提交于 2019-11-26 22:24:21

问题


  • I am communicating with a server who needs null terminated string
  • How can I do this smartly in C#?

回答1:


I assume you're implementing some kind of binary protocol, if the strings are null terminated. Are you using a BinaryWriter?

The default BinaryWriter writes strings as length prefixed. You can change that behavior:

class MyBinaryWriter : BinaryWriter
{
    private Encoding _encoding = Encoding.Default;

    public override void Write(string value)
    {
        byte[] buffer = _encoding.GetBytes(value);
        Write(buffer);
        Write((byte)0);
    }
}

Then you can just write any string like this:

using (MyBinaryWriter writer = new MyBinaryWriter(myStream))
{
    writer.Write("Some string");
}

You may need to adjust the _encoding bit, depending on your needs.

You can of course expand the class with specific needs for other data types you might need to transfer, keeping your actual protocol implementation nice and clean. You'll probably also need your own (very similar) BinaryReader.




回答2:


I think the smart way is to do it simply.

string str = "An example string" + char.MinValue; // Add null terminator.

Then convert it into bytes to send to the server.

byte[] buffer = ASCIIEncoding.ASCII.GetBytes(str);

Of course what encoding you use depends on what encoding the server expects.




回答3:


The strings are already null terminated. Although the string itself doesn't contain a null character, a null character always follows the string in memory.

However, strings in .NET are unicode, so they are stored as UTF-16/UCS-2 in memory, and the server might expect a different encoding, usually an 8 bit encoding. Then you would have to encode the string into a byte array and place a zero byte at the end:

byte[] data = Encoding.Default.GetBytes(theString);
byte[] zdata = new byte[data.Length + 1];
data.CopyTo(zdata, 0);

(The zdata array is all filled with zeroes when creates, so you don't have to actually set the extra byte to zero.)




回答4:


You add a null character to the end of the string. .NET strings can contain null characters.



来源:https://stackoverflow.com/questions/2793548/how-to-get-a-null-terminated-string-from-a-c-sharp-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!