Getting null terminated string from System.Text.Encoding.Unicode.GetString

[亡魂溺海] 提交于 2019-11-29 13:39:30

If you're sure the rest is all \0, this would work:

cmd = cmd.TrimEnd('\0');

Otherwise, if you just want to get everything before the first null:

int index = cmd.IndexOf('\0');
if (index >= 0)
   cmd = cmd.Remove(index);

Note that Unicode.GetString will take care of double \0s. You should just look for a single \0.

The easiest way would be to trim the string after conversion, as already suggested.

If you know the character count in advance, you could use the GetString overload that takes a start index and a count of bytes, in order to get the correct string, without trimming.

If you do not know the character count in advance, and would like to avoid trimming the string afterwards, you need to trim the byte array first, so you only pass the bytes you are interested in. For Unicode, this would mean removing any bytes after and including the first pair of zeroes.

Rather than reprocessing the string you can get the first occurrence of the null byte in the buffer (using System.Array.IndexOf). You can then use the overloaded System.Text.Encoding.Unicode.GetString method to create a string up to the given buffer size.

The example below also caters for a buffer containing no null bytes:

byte[] buffer = new byte[buffSize];
m_dataStream.Read(buffer, 0, buffSize);
var size = System.Array.IndexOf(buffer, (byte)0);
String cmd = System.Text.Encoding.Unicode.GetString(buffer, 0, size < 0 ? buffSize : size);
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!