Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

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

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  E  L  L       ... 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..."

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

cmd = cmd.TrimEnd('');

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

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...