我有一个布尔值字符串,我想用这些布尔值作为位来创建一个二进制文件。这就是我要做的:
# 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个字节的输出,而且速度很慢。有什么更有效的方法呢?在
可以使用
data = long(boolString,2)
将布尔字符串转换为long
。然后,要将此长数据写入磁盘,您可以使用:但是,不需要生成布尔字符串。使用
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
如果你先计算所有字节,然后把它们写在一起,应该会更快。例如
我还使用了一个
bytearray
,这是一个可以使用的自然容器,也可以直接写入到文件中。在如果合适,当然可以使用库,例如bitarray和{a2}。用后者你可以说
^{pr2}$相关问题 更多 >
编程相关推荐