【发布时间】:2012-09-22 05:40:49
【问题描述】:
我有一串布尔值,我想用这些布尔值作为位来创建一个二进制文件。这就是我正在做的:
# 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 个字节并且速度很慢。什么是更有效的方法?
【问题讨论】:
-
我在过去发现 BitVector 模块很方便 - pypp:pypi.python.org/pypi/BitVector/3.1.1 和主页:engineering.purdue.edu/kak/dist/BitVector-3.1.1.html
-
老实说,我有点希望有一个标准库解决方案。
标签: python file-io binary binaryfiles