获得空结尾的字符串从System.Text.Encoding.Uni code.GetString [英] Getting null terminated string from System.Text.Encoding.Unicode.GetString

查看:182
本文介绍了获得空结尾的字符串从System.Text.Encoding.Uni code.GetString的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有我从外部实体接收的字节数组。它是一个固定的大小。该字节包含一个单code字符串,用0值来填补缓冲区的其余部分:

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:

所以字节可能是:

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

我怎么能告诉的GetString终止在第一次统一code空的字符串(例如,所以我只是回来HELLO)?

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

感谢您的任何输入。

推荐答案

如果你确定其余全\ 0,这会工作:

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

注意统一code.GetString 将采取双\ 0照顾。你应该只是寻找一个'\ 0。

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

这篇关于获得空结尾的字符串从System.Text.Encoding.Uni code.GetString的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆