2

我有一串布尔值,我想使用这些布尔值作为位创建一个二进制文件。这就是我正在做的事情:

# 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 个字节并且速度很慢。什么是更有效的方法呢?

4

6 回答 6

2

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

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

我也在使用一个bytearray自然容器,也可以直接写入你的文件。


如果合适的话,您当然可以使用库,例如​​ bitarraybitstring。使用后者你可以说

bitstring.Bits(bin=boolString).tofile(outputFile)
于 2012-10-01T11:32:30.637 回答
2

这是另一个答案,这一次使用来自PyCrypto - 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
于 2012-10-01T22:34:06.873 回答
1

您可以使用数组类尝试此代码:

import array

buffer = array.array('B')

i = 0
while i < len(boolString) / 8:
    byte = int(boolString[i*8 : (i+1)*8], 2)
    buffer.append(byte)
    i += 1

f = file(filename, 'wb')
buffer.tofile(f)
f.close()
于 2012-10-01T11:31:12.510 回答
1

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

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

但是,不需要创建一个布尔字符串。使用long. 该long类型可以包含无限数量的位。使用位操作,您可以根据需要设置或清除位。然后,您可以在单个写入操作中将 long 写入整个磁盘。

于 2012-10-01T11:32:04.633 回答
1

一个助手类(如下所示)使它变得容易:

class BitWriter:
    def __init__(self, f):
        self.acc = 0
        self.bcount = 0
        self.out = f

    def __del__(self):
        self.flush()

    def writebit(self, bit):
        if self.bcount == 8 :
            self.flush()
        if bit > 0:
            self.acc |= (1 << (7-self.bcount))
        self.bcount += 1

    def writebits(self, bits, n):
        while n > 0:
            self.writebit( bits & (1 << (n-1)) )
            n -= 1

    def flush(self):
        self.out.write(chr(self.acc))
        self.acc = 0
        self.bcount = 0

with open('outputFile', 'wb') as f:
    bw = BitWriter(f)
    bw.writebits(int(boolString,2), len(boolString))
    bw.flush()
于 2012-10-01T13:25:03.410 回答
0

使用struct

这可用于处理存储在文件中或来自网络连接以及其他来源的二进制数据。

编辑:

?用作.格式字符的示例bool

import struct

p = struct.pack('????', True, False, True, False)
assert p == '\x01\x00\x01\x00'
with open("out", "wb") as o:
    o.write(p)

让我们看一下文件:

$ ls -l out
-rw-r--r-- 1 lutz lutz 4 Okt  1 13:26 out
$ od out
0000000 000001 000001
000000

再读一遍:

with open("out", "rb") as i:
    q = struct.unpack('????', i.read())
assert q == (True, False, True, False)
于 2012-10-01T11:15:41.147 回答