python解包的概念_如何以编程方式为解包结构?

我试图用Python读取和解析一个二进制文件。在

问题是文件中的数据可以是little-endian或big-endian格式,也可以是32位或64位的值。在文件头中有几个字节指定数据格式和大小。假设我已经读过这些,并且知道格式和大小,然后尝试构造一个格式字符串,如下所示:if (bitOrder == 1): # little-endian format

strData = '

elif (bitOrder == 2): # bit-endian format

strData = '>'

if (dataSize == 1): # 32-bit data

strLen = 'L'

elif (dataSize == 2):

strLen = 'q'

strFormat = strData + strLen

struct.unpack(strFormat, buf)

当我这样做时,我得到了错误:"struct.error: unpack requires a string argument of length 2",但是如果我写struct.unpack('

在交互式shell上,如果我运行type(strFormat)我得到结果,当我运行len(strFormat)时,我得到2的结果。在

因此,作为Python的新手,我有以下几个问题:str与字符串不一样吗?如果没有,我如何在两者之间转换?

如何正确构造用于unpack函数的格式字符串?

------编辑------

处理意见:由于其他项目的限制,我现在使用python-2.7。

我试图避免发布我的代码(它有几百行长),但是这里有一个interact python(从emacs内部运行,如果有关系的话),它显示了我所经历的行为:Python 2.7.5 (default, Jun 17 2014, 18:11:42)

[GCC 4.8.2 20140120 (Red Hat 4.8.2-16)] on linux2

Type "help", "copyright", "credits" or "license" for more information.

>>> >>> >>> >>>

>>> import array

>>> import struct

>>> header = array.array('B',[0x7f, 0x45, 0x4c, 0x46, 0x02, 0x01, 0x01, 0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00, 0x00, 0x02, 0x00,0x3e, 0x00, 0x01, 0x00, 0x00, 0x00, 0x40, 0x04, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x70, 0x11, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x00,0x00, 0x00, 0x00, 0x40, 0x00, 0x38, 0x00, 0x09, 0x00, 0x40, 0x00, 0x1e, 0x00, 0x1b, 0x00])

>>> entry = header[24:32]

>>> phoff = header[32:40]

>>> shoff = header[40:48]

>>> strData = '

>>> strLen = 'H'

>>> strFormat = strData + strLen

>>> print strFormat

>>> type(strFormat)

>>> len(strFormat)

2

>>> temp = struct.unpack(strFormat, entry)

Traceback (most recent call last):

File "", line 1, in

struct.error: unpack requires a string argument of length 2

>>>

修复了原始代码中的类型。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值