简体   繁体   English

为什么我的 Python 读取的位比我设置的多?

[英]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.

相关问题 为什么我的for循环运行的次数超过我指定的次数? - Why does my for loop run more times than I specify? 当我的文本文件明显多于 1 行时,为什么会出现此错误? - Why does this error occur when my text files have clearly more than 1 lines? 如果我执行一个以上的纪元,为什么我的keras模型会终止并冻结我的笔记本? - Why does my keras model terminate and freeze my notebook if I do more than one epoch? 为什么我不能在Python中读取超过16个字节的JPEG文件? - Why can I not read more than 16 bytes of a JPEG file in Python? 为什么我的Python类声称我有2个参数而不是1? - Why does my Python class claim that I have 2 arguments instead of 1? 为什么 meshgrid 比输入多一维? - Why does meshgrid have one more dimension than input? 为什么一个输入比另一个输入具有更大的权重 - Why does one input have much more weight than another 为什么 str(float) 在 Python 3 中比 Python 2 返回更多的数字? - Why does str(float) return more digits in Python 3 than Python 2? 为什么我不能在 Python 中使用 OpenCV 使用我的网络摄像头多次捕获? - Why can't I capture with my webcam more than once with OpenCV in Python? 以“rb”模式读取的 Python 文件返回一个字节字符串,其字节数超过 8 位和非十六进制字符? - Python file reading in "rb" mode returns a byte string that have bytes of more than 8 bits and non-hex characters?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM