从Python中的二进制文件中读取整数 [英] Reading integers from binary file in Python

查看:1452
本文介绍了从Python中的二进制文件中读取整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想读 BMP在Python 文件。我知道前两个字节
表明BMP公司。在接下来的4个字节是文件大小。当我excecute:

I'm trying to read a BMP file in Python. I know the first two bytes indicate the BMP firm. The next 4 bytes are the file size. When I excecute:

fin = open("hi.bmp", "rb")
firm = fin.read(2)  
file_size = int(fin.read(4))  

我得到

ValueError错误:无效的字面INT()基数为10:'F#\\ X13

ValueError: invalid literal for int() with base 10: 'F#\x13'

我想要做的就是读那些四个字节作为一个整数...看来Python的是阅读他们的字符并返回一个字符串,它不能转换为整数。我怎么能这样做是否正确?

What I want to do is reading those four bytes as an integer... It seems Python is reading them as characters and returning a string, which cannot be converted to an integer. How can I do this correctly?

推荐答案

方法返回字节字符串序列。从字符串的字节序列为二进制数据转换,使用内置的结构模块:的 http://docs.python.org/library/struct.html

The read method returns a sequence of bytes as a string. To convert from a string byte-sequence to binary data, use the built-in struct module: http://docs.python.org/library/struct.html.

import struct

print(struct.unpack('i', fin.read(4)))

注意解压总是返回一个元组,因此 struct.unpack('我',fin.read(4))[0] 给你是后的整数值。

Note that unpack always returns a tuple, so struct.unpack('i', fin.read(4))[0] gives the integer value that you are after.

您应该使用格式字符串'<我(小于是一个修饰符,表示little-endian字节顺序和标准大小和对齐方式 - 默认是使用平台的字节顺序,大小和取向)。按照BMP格式规范,字节应该写在英特尔/ little-endian字节顺序。

You should probably use the format string '<i' (< is a modifier that indicates little-endian byte-order and standard size and alignment - the default is to use the platform's byte ordering, size and alignment). According to the BMP format spec, the bytes should be written in Intel/little-endian byte order.

这篇关于从Python中的二进制文件中读取整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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