除去字节数组尾随空在C# [英] Removing trailing nulls from byte array in C#

查看:323
本文介绍了除去字节数组尾随空在C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好吧,我读的DAT文件成字节数组。出于某种原因,谁生成这些文件放大约一个半兆的价值无用空人民字节在文件的结尾。任何人都知道一个快速的方法来削减这些关到底?

Ok, I am reading in dat files into a byte array. For some reason, the people who generate these files put about a half meg's worth of useless null bytes at the end of the file. Anybody know a quick way to trim these off the end?

首先想到的是开始在数组的末尾和向后迭代,直到我发现多了一个零以外的东西,然后一切都复制到这一点,但我不知道如果没有更好的办法

First thought was to start at the end of the array and iterate backwards until I found something other than a null, then copy everything up to that point, but I wonder if there isn't a better way.

要回答一些问题:
你确定了0字节肯定是在文件中,而不是出现在被文件读取代码中的错误?是的,我可以肯定。

To answer some questions: Are you sure the 0 bytes are definitely in the file, rather than there being a bug in the file reading code? Yes, I am certain of that.

你能肯定修剪所有尾随0?是的。

Can you definitely trim all trailing 0s? Yes.

能否会有在文件的其余部分的0?是的,有可能是0的其他地方,所以,不,我不能从头开始,并在第一个0停下来。

Can there be any 0s in the rest of the file? Yes, there can be 0's other places, so, no, I can't start at the beginning and stop at the first 0.

推荐答案

由于现在回答的问题外,它听起来就像你根本做正确的事。特别是,你必须从最后的0起,触摸文件的每个字节,以检查它只有0。

Given the extra questions now answered, it sounds like you're fundamentally doing the right thing. In particular, you have to touch every byte of the file from the last 0 onwards, to check that it only has 0s.

现在,你是否有复制的一切或不取决于什么你然后用数据做什么。

Now, whether you have to copy everything or not depends on what you're then doing with the data.


  • 您或许还记得指数和与数据或文件名保持。

  • 您可以将数据复制到一个新的字节数组

  • 如果你想修理的文件,你可以调用的FileStream.SetLength 截断文件

  • You could perhaps remember the index and keep it with the data or filename.
  • You could copy the data into a new byte array
  • If you want to "fix" the file, you could call FileStream.SetLength to truncate the file

你的有无的阅读截断点和文件末尾之间的每个字节是虽然重要组成部分。

The "you have to read every byte between the truncation point and the end of the file" is the critical part though.

这篇关于除去字节数组尾随空在C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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