Last active
December 22, 2015 14:59
-
-
Save maxdeliso/6489370 to your computer and use it in GitHub Desktop.
string to binary program in python 3, using CLI, coded in functional style
This file contains hidden or 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
### b2t.py - little program to convert strings to/from binary ### | |
### note: functional style emphasized. | |
### http://docs.python.org/dev/howto/functional | |
### | |
### by Max DeLiso ### | |
## IMPORTS ## | |
import re # regular expression module to recognize binary strings | |
import os # operating system interface for retrieving current directory | |
from datetime import datetime # for retrieving clock value as a string | |
## CONSTANTS ## | |
B2T_TRANSCRIPT_FILE='b2t.txt' | |
ENCODE_PROMPT='e>> ' | |
DECODE_PROMPT='d>> ' | |
ENCODE_CHAR='e' | |
DECODE_CHAR='d' | |
## ROUTINES ## | |
def encodeLoop(tf): | |
try: | |
while True: | |
echoAndSave(' '.join( | |
map(lambda ch: str(bin(ord(ch))[2:]), | |
input(ENCODE_PROMPT))), tf) | |
except EOFError: | |
pass | |
def attemptDecode(rawStr): | |
try: | |
return str(chr(int(rawStr, base=2))) | |
except ValueError: | |
pass | |
except UnicodeEncodeError: | |
pass | |
def decodeLoop(tf): | |
try: | |
while True: | |
echoAndSave(''.join( | |
filter(None, | |
list(map(attemptDecode, | |
re.findall(r'[0-1]+', input(DECODE_PROMPT)))))), tf) | |
except EOFError: | |
pass | |
def echoAndSave(coded, tf): | |
print(coded) | |
tf.write("{}\n".format(coded)) | |
## ENTRY ## | |
if __name__ == '__main__': | |
# get handle to transcript file | |
tf = open(B2T_TRANSCRIPT_FILE, 'a') | |
# write the time | |
tf.write('starting up at {}\n'.format(datetime.now().ctime())) | |
# get user choice for mode | |
userChoice = '' | |
while userChoice != ENCODE_CHAR and userChoice != DECODE_CHAR: | |
print('{} for encode, {} for decode'.format(ENCODE_CHAR, DECODE_CHAR)) | |
userChoice = input('mode? ').lower()[0] | |
# remind user how to quit | |
print('CTRL-Z + Enter quits') | |
# enter into main i/o loop | |
if userChoice == ENCODE_CHAR: | |
tf.write('entering encode mode\n') | |
encodeLoop(tf) | |
elif userChoice == DECODE_CHAR: | |
tf.write('entering decode mode\n') | |
decodeLoop(tf) | |
# write the time | |
tf.write('shutting down at {}\n'.format(datetime.now().ctime())) | |
# close transcript file handle | |
tf.close() | |
# remind user where the transcript is | |
print('!! transcript saved in {} in dir {} !!'. | |
format(B2T_TRANSCRIPT_FILE, | |
os.getcwd())) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment