Created
December 29, 2022 02:10
-
-
Save benaclejames/953593890a5e1a3bf2952ddcc45308c8 to your computer and use it in GitHub Desktop.
Yipify
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 sys | |
def yipify(input_file, output_file): | |
# Open the input and output files | |
with open(input_file, 'rb') as infile, open(output_file, 'w') as outfile: | |
# Read the input file, one byte at a time | |
byte = infile.read(1) | |
while byte: | |
# Convert the byte to a binary string | |
binary = format(ord(byte), 'b') | |
# Prepend 0s to the binary string until it is 8 characters long | |
binary = binary.zfill(8) | |
# Write "yip" for every 1 and "yap" for every 0 in the binary string | |
outfile.write(''.join(["yip" if ch == "1" else "yap" for ch in binary])) | |
# Read the next byte | |
byte = infile.read(1) | |
def decode(input_file, output_file): | |
# Open the input and output files | |
with open(input_file, 'r') as infile, open(output_file, 'wb') as outfile: | |
# Read the input file, one character at a time | |
char = infile.read(3) | |
# Initialize an empty binary string | |
binary = "" | |
while char: | |
# If the character is "yip", add a "1" to the binary string | |
if char == "yip": | |
binary += "1" | |
# If the character is "yap", add a "0" to the binary string | |
elif char == "yap": | |
binary += "0" | |
# If the binary string has 8 characters (a full byte), convert it to a byte and write it to the output file | |
if len(binary) == 8: | |
outfile.write(bytes([int(binary, 2)])) | |
# Reset the binary string | |
binary = "" | |
# Read the next character | |
char = infile.read(3) | |
def main(): | |
# Check that the correct number of arguments were provided | |
if len(sys.argv) != 4: | |
print("Usage: python yipify.py [mode] [input file] [output file]") | |
sys.exit(1) | |
# Get the mode, input and output filenames | |
mode = sys.argv[1] | |
input_file = sys.argv[2] | |
output_file = sys.argv[3] | |
# Check the mode and call the appropriate function | |
if mode == "encode": | |
yipify(input_file, output_file) | |
elif mode == "decode": | |
decode(input_file, output_file) | |
else: | |
print("Invalid mode. Valid modes are 'encode' and 'decode'.") | |
sys.exit(1) | |
# Run the main function | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment