gpt4 book ai didi

python - 如何以编程方式构造 struct.unpack 的格式字符串?

转载 作者:太空宇宙 更新时间:2023-11-03 17:57:48 25 4
gpt4 key购买 nike

我正在尝试使用 Python 读取和解析二进制文件。

问题是文件中的数据可以是小端或大端格式,以及 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('<L', buf)我得到了预期的结果。

在交互式 shell 上,如果我运行 type(strFormat)我得到结果<type, 'str'>当我运行len(strFormat)时我得到的结果是 2 .

作为 Python 新手,我有以下问题:

  1. 不是str和字符串一样吗?如果不是,如何在两者之间进行转换?

  2. 如何正确构造用于 unpack 的格式字符串功能?

------编辑------处理评论:

  1. 由于其他项目的限制,我目前使用的是 python-2.7。

  2. 我试图避免发布我的代码(它有几百行长),但是这里有一个交互 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
    <H
    >>> type(strFormat)
    <type 'str'>
    >>> len(strFormat)
    2
    >>> temp = struct.unpack(strFormat, entry)
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    struct.error: unpack requires a string argument of length 2
    >>>
  3. 修复了原始代码中的类型。

最佳答案

根据交互式 session ,您的问题似乎是这样的:

temp = struct.unpack(strFormat, entry)

之前,您说过:

entry = header[24:32]

entry 是 8 个字节长,但 strFormat 说它应该是 2 个字节长。这就是 struct 所提示的。

它也应该是一个 bytes 对象(2.x 下的 str),而不是 array.array

关于python - 如何以编程方式构造 struct.unpack 的格式字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28240767/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com