[英]Why does my Python read more bits than I have set?
I'm trying to read the values from a binary file but I'm having some trouble.我正在尝试从二进制文件中读取值,但遇到了一些麻烦。 This is what I'm doing:
这就是我正在做的:
from struct import unpack
with open("pixelValues.txt", "rb") as f:
byte = f.read(8)
foo = unpack("<Q", byte)
print(foo)
When I run the program the output is (4244912790557L,)
which doesn't make sense to me because it should be 1485102109
.当我运行程序时,输出是
(4244912790557L,)
这对我来说没有意义,因为它应该是1485102109
。 Does anyone see what I'm doing wrong?有没有人看到我做错了什么?
Here is a screenshot of the file:这是文件的屏幕截图:
You're reading too much.你读得太多了。 Change
f.read(8)
to f.read(4)
and change unpack("<Q", byte)
to unpack("i", byte)
and that will fix your problem.将
f.read(8)
更改为f.read(4)
并将unpack("<Q", byte)
更改为unpack("i", byte)
,这将解决您的问题。
pack('<Q', 1485102109)
Returns:返回:
'\x1d\xdc\x84X\x00\x00\x00\x00'
Which is not consistent with your file.这与您的文件不一致。 How did you write it?
你是怎么写的?
Edit:编辑:
You have written the number with a %d specifier, which means that you've written it as a 4-byte integer, not as an unsigned long long, but as an unsigned int.您已使用 %d 说明符编写了数字,这意味着您已将其编写为 4 字节整数,而不是 unsigned long long,而是 unsigned int。 You should read it like this:
你应该这样读:
from struct import unpack
with open("pixelValues.txt", "rb") as f:
num = f.read(4)
foo = unpack("<I", num)
print(foo)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.