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

前端 未结 4 867
耶瑟儿~
耶瑟儿~ 2020-12-03 13:49
  • I am communicating with a server who needs null terminated string
  • How can I do this smartly in C#?
4条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 14:40

    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.)

提交回复
热议问题