读取InputStream的头问题
我正在尝试读取 InputStream
文件的标头。每个标题信息都包含信息。但是,我很难理解读取标题的过程。
例如,我有:
InputStream sourceFile = //.... stuff.
sourceFile.read() | (sourceFile.read() << 8) | (sourceFile.read() << 16)
| (sourceFile.read() << 24)
来自示例代码。
为什么我不只使用一次 sourceFile.read()
呢?单个 |
是什么意思,<< 是什么意思? number
在这个特定的上下文中意味着什么?
感谢您的任何澄清!
I'm trying to read the header of an InputStream
file. Every header info contains information. However, I have trouble to understand the process of reading the header.
For example, I have:
InputStream sourceFile = //.... stuff.
sourceFile.read() | (sourceFile.read() << 8) | (sourceFile.read() << 16)
| (sourceFile.read() << 24)
from an example code.
Why don't I just use sourceFile.read()
once? What does the single |
means and what does << number
in this particular context mean?
Thanks for any clarification!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
read()
返回int
,但它从文件中读取一个字节,因此想法是获取前 4 个字节并将它们转换为 32 位 int(而更改其字节序)。您所指的运算符是二元运算符和位运算符。请参阅此处了解更多信息。
read()
returnsint
, but it reads one byte from the file, so the idea is to get the first 4 bytes and convert them to a 32-bit int (while changing their endianness).The operators you refer to are binary and bitwise operators. please refer here for more information.
听起来您在这里对术语有点困惑 - 标头是文件的第一部分,但输入流只是用于从该文件读取的流。没有“InputStream 文件”。每个文件的标头也不同 - 所有文件都没有标准的“标头格式”。
这段特定代码的作用似乎是从文件中读取第一个 32 位整数(需要多次读取,因为每个 read() 调用仅读取一个字节。)
就 << 而言,这是一个左移位运算符,其后面的数字决定要移位的位数。数字从 8 增加到 16 再到 24,因为这些位被移位到正确的位置(一个字节中有 8 位,因此每次移位的数字增加 8。)
It sounds like you're getting terms a bit confused here - the header is the first part of a file but the inputstream is just the stream used to read from that file. There's no "InputStream file". Headers are also different for each file - there's no standard "header format" for all files.
What it seems this particular piece of code is doing is reading the first 32 bit integer from the file (the multiple reads are needed because each read() call just reads one byte.)
In terms of the <<, that's a left shift operator, and the number after it determines the number of bits to shift along. The numbers increase from 8 to 16 to 24 because the bits are being shifted to their correct position (8 bits in a byte, so the number to shift increases by 8 each time.)