views:

795

answers:

2

I have an array of bytes that I receive from an external entity. It is a fixed size. The bytes contain a unicode string, with 0 values to pad out the rest of the buffer:

So the bytes might be:

H \0 E \0 L \0 L \0 \0 \0 \0 \0 \0 ... etc

I'm getting that buffer and converting it to a string like so:

byte[] buffer = new byte[buffSize];
m_dataStream.Read(buffer, 0, buffSize);
String cmd = System.Text.Encoding.Unicode.GetString(buffer);

What I get back is a string that looks like this:

"HELLO\0\0\0\0\0\0\0\0..."

How can I tell GetString to terminate the string at the first Unicode null (ie so I just get back "HELLO")?

Thanks for any input.

+1  A: 

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.

Mehrdad Afshari
A: 

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.

driis