简体   繁体   English

FileStream.Read(...):我会得到一个半字节而不是字节吗?

[英]FileStream.Read(…): Will I ever get a nibble rather than byte?

I'm doing a number of bitwise operations on an array of bytes in C#. 我正在对C#中的字节数组进行一些按位操作。 I'm obtaining the array by calling FileStream.Read. 我通过调用FileStream.Read获取数组。 I just realized that I'm not sure what would happen if a file had a bad byte or corrupt byte in it somewhere. 我刚才意识到,我不确定如果一个文件在某个地方有一个错误的字节或损坏的字节会发生什么。 For example, maybe a nibble is chopped off of the end or something like that. 例如,可能会从末端切断半字节或类似的东西。 What would the FileStream do with it? FileStream会用它做什么? Would the messed up byte by 'rounded' off by the Read method? 通过Read方法将'四舍五入'的字节弄乱了吗? Would an exception be thrown? 是否会抛出异常? Or is this something that will virtually never happen? 或者这是否几乎不会发生?

Thanks, brian 谢谢,布莱恩

If your FileStream.Read call succeeds, there's no such thing as a file having a bad byte or corrupt byte. 如果你的FileStream.Read调用成功,那么就没有文件具有错误的字节或损坏的字节。 Each byte that is successfully read, and part of the file, is a value from 0 to 255. How it is interpreted by a program is what matters. 成功读取的每个字节和文件的一部分是0到255之间的值。程序如何解释它是最重要的。

If FileStream.Read returns for example 5 bytes, then you can rely that those 5 bytes are read successfully from the file and all bits of the bytes were put into your buffer successfully. 如果FileStream.Read返回例如5个字节,那么您可以依赖从文件中成功读取这5个字节,并且所有字节位都成功地放入缓冲区。

There is such thing though for example as a bad cluster on your hard disk, in which case your Read would fail with some kind of exception. 例如,作为硬盘上的坏簇,有这样的事情,在这种情况下,您的Read会因某种异常而失败。

For completeness I should also mention that every file type has a file format. 为了完整起见,我还应该提到每种文件类型都有文件格式。 Ie how you should interpret the binary data. 即你应该如何解释二进制数据。 It is possible that a byte or several bytes don't follow the file format. 一个字节或几个字节可能不遵循文件格式。 And in that way you can view a byte as being corrupt or invalid, but it's not really corrupt or invalid just wrong in terms of what the file format specifies. 通过这种方式,您可以将一个字节视为已损坏或无效,但就文件格式指定的内容而言,它并不是真正的损坏或无效。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM