从System.Text.Encoding.Unicode.GetString获取空终止的字符串

编程入门 行业动态 更新时间:2024-10-23 19:20:04
本文介绍了从System.Text.Encoding.Unicode.GetString获取空终止的字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个我从外部实体收到的字节数组。它是一个固定的大小。字节包含一个unicode字符串,其中0个值用于填充缓冲区的其余部分:

所以字节可能是:

$ $ $ $ $ $ $

我正在获得该缓冲区并将其转换为如下所示的字符串:

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

我回来的是一个如下所示的字符串:

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

如何告诉GetString在第一个Unicode null处终止字符串(即所以我刚回到HELLO)?

感谢任何输入。

解决方案

如果你确定其余的都是\0,这将工作:

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

否则,如果您只想在第一个null之前获得所有内容:

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

请注意, Unicode.GetString 将照顾的双\0s。你应该只找一个\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:

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.

解决方案

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.

更多推荐

从System.Text.Encoding.Unicode.GetString获取空终止的字符串

本文发布于:2023-11-10 06:23:59,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1574599.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:字符串   Text   System   Encoding   GetString

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!