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

时间:2012-10-01 11:12:09

标签: python file-io binary binaryfiles

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

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

6 个答案:

答案 0 :(得分: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)

答案 1 :(得分:2)

这是另一个答案,这次是使用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

答案 2 :(得分:1)

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

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()

答案 3 :(得分:1)

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

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

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

答案 4 :(得分:1)

helper class(如下所示)简化:

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()

答案 5 :(得分:0)

使用struct package

  

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

修改

使用?作为bool的{​​{3}}的示例。

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)