Skip to content

Instantly share code, notes, and snippets.

@gngdb
Created August 27, 2018 10:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gngdb/3781ec8cba30769f881e9f9cbd54ed36 to your computer and use it in GitHub Desktop.
Save gngdb/3781ec8cba30769f881e9f9cbd54ed36 to your computer and use it in GitHub Desktop.
Save a string of ones and zeros as those ones and zeros in binary using Python.
import random
from io import StringIO
def write_bitstream(fname, bits):
# bits are a string of ones and zeros, based on this
# stackoverflow answer: https://stackoverflow.com/a/16888829/6938913
# was broken due to utf-8 encoding using up to 4 bytes: https://stackoverflow.com/a/33349765/6937913
sio = StringIO(bits)
with open(fname, 'wb') as f:
while 1:
# Grab the next 8 bits
b = sio.read(8)
# Bail if we hit EOF
if not b:
break
# If we got fewer than 8 bits, pad with zeroes on the right
if len(b) < 8:
b = b + '0' * (8 - len(b))
# Convert to int
i = int(b, 2)
# Write
f.write(i.to_bytes(1, byteorder='big'))
if __name__ == '__main__':
# generate a string of just zeros and ones
random.seed(0)
s = list("0"*1000 + "1"*1000)
random.shuffle(s)
s = "".join(s)
print(len(s)/8)
write_bitstream("bits", s)
@G7itch
Copy link

G7itch commented Jan 13, 2023

This is the most beautiful thing I've ever seen. you've solved all of my problems. I... I think i'm in love with your code

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment