Created
August 27, 2018 10:48
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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