将布尔字符串写入二进制文件?

2024-09-30 10:27:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个布尔值字符串,我想用这些布尔值作为位来创建一个二进制文件。这就是我要做的:

# first append the string with 0s to make its length a multiple of 8
while len(boolString) % 8 != 0:
    boolString += '0'

# write the string to the file byte by byte
i = 0
while i < len(boolString) / 8:
    byte = int(boolString[i*8 : (i+1)*8], 2)
    outputFile.write('%c' % byte)

    i += 1

但这一次只产生1个字节的输出,而且速度很慢。有什么更有效的方法呢?在


Tags: 文件theto字符串stringmakelenwith
3条回答

可以使用data = long(boolString,2)将布尔字符串转换为long。然后,要将此长数据写入磁盘,您可以使用:

while data > 0:
    data, byte = divmod(data, 0xff)
    file.write('%c' % byte)

但是,不需要生成布尔字符串。使用long要容易得多。long类型可以包含无限数量的位。使用位操作,您可以根据需要设置或清除位。然后,您可以在一次写入操作中将long作为一个整体写入磁盘。在

这是另一个答案,这次使用了来自PyCrypto - The Python Cryptography Toolkit的工业强度实用函数,在版本2.6(当前最新的稳定版本)中,它在pycrypto-2.6/lib/Crypto/Util/number.py中定义。在

前面的评论说:
Improved conversion functions contributed by Barry Warsaw, after careful benchmarking

import struct

def long_to_bytes(n, blocksize=0):
    """long_to_bytes(n:long, blocksize:int) : string
    Convert a long integer to a byte string.

    If optional blocksize is given and greater than zero, pad the front of the
    byte string with binary zeros so that the length is a multiple of
    blocksize.
    """
    # after much testing, this algorithm was deemed to be the fastest
    s = b('')
    n = long(n)
    pack = struct.pack
    while n > 0:
        s = pack('>I', n & 0xffffffffL) + s
        n = n >> 32
    # strip off leading zeros
    for i in range(len(s)):
        if s[i] != b('\000')[0]:
            break
    else:
        # only happens when n == 0
        s = b('\000')
        i = 0
    s = s[i:]
    # add back some pad bytes.  this could be done more efficiently w.r.t. the
    # de-padding being done above, but sigh...
    if blocksize > 0 and len(s) % blocksize:
        s = (blocksize - len(s) % blocksize) * b('\000') + s
    return s

如果你先计算所有字节,然后把它们写在一起,应该会更快。例如

b = bytearray([int(boolString[x:x+8], 2) for x in range(0, len(boolString), 8)])
outputFile.write(b)

我还使用了一个bytearray,这是一个可以使用的自然容器,也可以直接写入到文件中。在


如果合适,当然可以使用库,例如bitarray和{a2}。用后者你可以说

^{pr2}$

相关问题 更多 >

    热门问题