Write Boolean String To Binary File?
Solution 1:
It should be quicker if you calculate all your bytes first and then write them all together. For example
b = bytearray([int(boolString[x:x+8], 2) for x inrange(0, len(boolString), 8)])
outputFile.write(b)
I'm also using a bytearray
which is a natural container to use, and can also be written directly to your file.
You can of course use libraries if that's appropriate such as bitarray and bitstring. Using the latter you could just say
bitstring.Bits(bin=boolString).tofile(outputFile)
Solution 2:
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
deflong_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 zerosfor i inrange(len(s)):
if s[i] != b('\000')[0]:
breakelse:
# 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 > 0andlen(s) % blocksize:
s = (blocksize - len(s) % blocksize) * b('\000') + s
return s
Solution 3:
You can convert a boolean string to a long
using data = long(boolString,2)
. Then to write this long to disk you can use:
whiledata > 0:
data, byte = divmod(data, 0xff)
file.write('%c' % byte)
However, there is no need to make a boolean string. It is much easier to use a long
. The long
type can contain an infinite number of bits. Using bit manipulation you can set or clear the bits as needed. You can then write the long to disk as a whole in a single write operation.
Solution 4:
You can try this code using the array class:
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()
Solution 5:
A helper class (shown below) makes it easy:
classBitWriter:
def__init__(self, f):
self.acc = 0
self.bcount = 0
self.out = f
def__del__(self):
self.flush()
defwritebit(self, bit):
if self.bcount == 8 :
self.flush()
if bit > 0:
self.acc |= (1 << (7-self.bcount))
self.bcount += 1defwritebits(self, bits, n):
while n > 0:
self.writebit( bits & (1 << (n-1)) )
n -= 1defflush(self):
self.out.write(chr(self.acc))
self.acc = 0
self.bcount = 0withopen('outputFile', 'wb') as f:
bw = BitWriter(f)
bw.writebits(int(boolString,2), len(boolString))
bw.flush()
Post a Comment for "Write Boolean String To Binary File?"