If the random, arbitrarily long sequence of bits represent a non-negative base 2 number, groups of 8 of those bits can be consider digits of a base-256 number and they can be written to a file as a string of 8-bit characters. Reversing the process after reading the string back in allows this string to be decoded back into the original number.
The following is something I derived from the this answer to the question Base 62 conversion in Python.
def base256_encode(n): # non-negative integer to byte string
if n > 0:
arr = []
while n:
n, rem = divmod(n, 256)
arr.append(chr(rem))
return ''.join(reversed(arr))
elif n == 0:
return '\x00'
else:
raise ValueError("can't convert negative value to a byte string")
def base256_decode(s): # (big-endian) byte string to number
return reduce(lambda a, c: a*256 + ord(c), s, 0)
def binrepr(s): # utility
return ' '.join(('{:08b}'.format(ord(c))) for c in s)
n = 173584
print 'n:', n
en = base256_encode(n)
print 'binary bytes:', binrepr(en)
with open('rawbits.bin', 'wb') as outf:
outf.write(en)
with open('rawbits.bin', 'rb') as inf:
print 'read from file:', base256_decode(inf.read())
Output:
n: 173584
binary bytes: 00000010 10100110 00010000
read from file: 173584