【问题标题】:Alternatives to using pack_into() when manipulating a list of bytes?处理字节列表时使用 pack_into() 的替代方法?
【发布时间】:2009-07-15 18:18:20
【问题描述】:

我正在将二进制文件读入列表并解析二进制数据。我正在使用 unpack() 将数据的某些部分提取为原始数据类型,并且我想编辑该数据并将其插入回原始字节列表中。使用pack_into() 会很容易,只是我使用的是 Python 2.4,并且 pack_into() 直到 2.5 才引入

有谁知道以这种方式序列化数据的好方法,以便我可以完成与 pack_into() 基本相同的功能?

【问题讨论】:

    标签: python binary struct


    【解决方案1】:

    您看过bitstring 模块吗?它旨在使二进制数据的构造、解析和修改比直​​接使用structarray 模块更容易。

    它特别适用于位级别,但也适用于字节。它也适用于 Python 2.4。

    from bitstring import BitString
    s = BitString(filename='somefile')
    
    # replace byte range with new values
    # The step of '8' signifies byte rather than bit indicies.
    s[10:15:8] = '0x001122'
    
    # Search and replace byte value with two bytes
    s.replace('0xcc', '0xddee', bytealigned=True)
    
    # Different interpretations of the data are available through properties
    if s[5:7:8].int > 1000:
        s[5:7:8] = 1000
    
    # Use the bytes property to get back to a Python string
    open('newfile', 'wb').write(s.bytes)
    

    BitString 中存储的底层数据只是一个array 对象,但具有一套全面的功能和特殊方法,使其易于修改和解释。

    【讨论】:

    • 这太棒了。
    【解决方案2】:

    您的意思是在缓冲区对象中编辑数据吗?关于直接从 Python 操作这些的文档相当稀缺。

    如果您只想编辑字符串中的字节,这很简单;不过; struct.pack_into 是 2.5 的新内容,但 struct.pack 不是:

    import struct
    s = open("file").read()
    ofs = 1024
    fmt = "Ih"
    size = struct.calcsize(fmt)
    
    before, data, after = s[0:ofs], s[ofs:ofs+size], s[ofs+size:]
    values = list(struct.unpack(fmt, data))
    values[0] += 5
    values[1] /= 2
    data = struct.pack(fmt, *values)
    s = "".join([before, data, after])
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 2021-01-11
      相关资源
      最近更新 更多