[ACCEPTED]-Getting null terminated string from System.Text.Encoding.Unicode.GetString-getstring

Accepted answer
Score: 15

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

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

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

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

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

Score: 4

For UTF8/ASCII encodings you can achieve 12 this without reprocessing the string by 11 looking for the first occurrence of the 10 null terminator in the buffer (using System.Array.IndexOf). You 9 can then use the overloaded System.Text.Encoding.Unicode.GetString method to create 8 a string up to the given buffer size.

The 7 example below also caters for a buffer containing 6 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);

For UTF16 you could use a 5 similar approach with a for loop (looking 4 for the first pair of null characters ... such 3 as if (buffer[i] == (byte)0 && buffer[i] == buffer[i+1]).

If creating temporary strings is of 2 no concern then the accepted answer is the 1 best solution.

Score: 2

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

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

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

Score: 0

You can get the length from Stream.Read()

int length = peerStream.Read(buffer, 0, buffer.Length);
receive = Encoding.UTF8.GetString(buffer, 0, length);

0

More Related questions