- I am communicating with a server who needs null terminated string
- How can I do this smartly in C#?
相关问题
- Sorting 3 numbers without branching [closed]
- Graphics.DrawImage() - Throws out of memory except
- Why am I getting UnauthorizedAccessException on th
- 求获取指定qq 资料的方法
- How to know full paths to DLL's from .csproj f
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:
(The zdata array is all filled with zeroes when creates, so you don't have to actually set the extra byte to zero.)
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:Then you can just write any string like this:
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
.You add a null character to the end of the string. .NET strings can contain null characters.
I think the smart way is to do it simply.
Then convert it into bytes to send to the server.
Of course what encoding you use depends on what encoding the server expects.