写布尔字符串到二进制文件? [英] Write boolean string to binary file?
问题描述
我有一串布尔值,我想用这些布尔值作为位来创建一个二进制文件。这是我正在做的:
#首先追加字符串0以使其长度为8的倍数b $ b while len(boolString)%8!= 0:
boolString + ='0'
#将字符串逐字节写入文件
i = 0
while我< len(boolString)/ 8:
byte = int(boolString [i * 8:(i + 1)* 8],2)
outputFile.write('%c'%byte)
i + = 1
但是这会产生输出1个字节, 。什么是更有效的方法呢?解决方案这是另一个答案,这次使用工业强度的效用函数 PyCrypto - Python加密工具包,在2.6版本(最新的稳定版本)中,它定义在 pycrypto-2.6 / lib / Crypto / Util / number.py
。
:
经过仔细的基准测试后,Barry Warsaw提供了改进的转换函数
导入结构
def long_to_bytes(n,blocksize = 0):
long_to_bytes(n:long,blocksize:int ):string
将一个长整数转换为一个字节字符串
如果给出了可选的blocksize并且大于0,则用$二进制零填充
字节的前面,长度是
blocksize的倍数。
经过多次测试,这个算法被认为是最快的
s = b('')
n = long(n)
pack = struct.pack
而n> 0:
s = pack('> I',n& 0xffffffffL)+ s
n = n>> (b)如果s [i]!= b('\ 000')[0]:
break
else:
#只在n == 0时发生
s = b('\000')
i = 0
s = s [i:]
#添加一些填充字节。这可以做得更有效率w.r.t.
#de-padding在上面完成,但感叹...
如果blocksize> 0和len(s)%blocksize:
s =(blocksize-len(s)%blocksize)* b('\ 000')+ s
return s
I have a string of booleans and I want to create a binary file using these booleans as bits. This is what I am doing:
# 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
But this generates the output 1 byte at a time and is slow. What would be a more efficient way to do it?
Here's another answer, this time using an industrial-strength utility function from the PyCrypto - The Python Cryptography Toolkit where, in version 2.6 (the current latest stable release), it's defined inpycrypto-2.6/lib/Crypto/Util/number.py
.
The comments preceeding it say:
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
这篇关于写布尔字符串到二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!