从字符串末尾修剪十六进制
我有一个字节数组,每个字节都用 0xFF 进行初始化:
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = 0xFF;
}
一旦该字节数组填充了有效数据,我需要提取存储在偏移量 192 处的 ASCII 字符串,长度最多可达 32 个字符。我这样做是这样的:
ASCIIEncoding enc = new ASCIIEncoding();
stringToRead = enc.GetString(buffer, 192, 32);
这可行,但我需要去掉包含 0xFF 的尾随字节,以避免字符串看起来像“John Smith?????????????????? ????”。 .NET 中有提供这种功能的函数吗?也许是类似 String.TrimEnd() 函数的东西,或者我正在寻找正则表达式来执行此操作?
I have a byte array that's been initialized with 0xFF in each byte:
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = 0xFF;
}
Once this byte array has been filled with valid data, I need to extract an ASCII string that's stored at offset 192 and may be up to 32 characters in length. I'm doing this like so:
ASCIIEncoding enc = new ASCIIEncoding();
stringToRead = enc.GetString(buffer, 192, 32);
This works but I need to strip off the trailing bytes that contain 0xFF to avoid the string looking something like "John Smith??????????????????????". Is there a function in .NET that provides this ability? Something like the String.TrimEnd() function perhaps or am I looking at a regex to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
我建议只找出字符串的长度真正:
我不会尝试提供无效的
Encoding.ASCII
字节ASCII 编码的文本。我不知道它会用它们做什么 - 我怀疑它会将它们转换为?
以显示错误(如您现有的输出所建议的),但是然后您将无法区分该问号和真正的问号。例如:现在您可以创建一个使用一些非ASCII替换字符的编码...但是当您只能找到二进制数据停止的位置时,这就很麻烦了是有效的。
I would suggest just finding out how long the string will really be:
I would not try to give
Encoding.ASCII
bytes which aren't valid ASCII-encoded text. I don't know offhand what it would do with them - I suspect it would convert them to?
to show the error (as suggested by your existing output), but then you wouldn't be able to tell the difference between that and real question marks. For example:Now you could create an encoding which used some non-ASCII replacement character... but that's a lot of hassle when you can just find where the binary data stops being valid.
或者,您可以扫描字符串以查找字符的第一个索引,然后获取子字符串:
Alternatively, you can scan the string for the first index of the character, then take the substring: