Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # 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
- b = bytearray([int(boolString[x:x+8], 2) for x in range(0, len(boolString), 8)])
- outputFile.write(b)
- bitstring.Bits(bin=boolString).tofile(outputFile)
- while data > 0:
- data, byte = divmod(data, 0xff)
- file.write('%c' % byte)
- 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()
- 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()
- 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 = ''
- 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] != '