Skip to content

Instantly share code, notes, and snippets.

@josharian
Last active December 22, 2015 22:29
Show Gist options
  • Save josharian/6540271 to your computer and use it in GitHub Desktop.
Save josharian/6540271 to your computer and use it in GitHub Desktop.
binconvtest.py from zach
import binascii
# To run doctests, do something like:
# python3 -m doctest binconvtest.py
def ascii_to_bin(input_string):
"""
ascii_to_bin converts a string of ASCII characters into a binary string
>>> ascii_to_bin("A")
b'41'
>>> ascii_to_bin("Testing...")
b'54657374696e672e2e2e'
"""
encoded = input_string.encode('ascii', 'strict')
return binascii.hexlify(encoded)
# return bin(int(binascii.hexlify(encoded), 16))
# This function, which converts a string of binary back into a string of
# ASCII characters, is the one I need help with:
def bin_to_ascii(input_binary):
"""
bin_to_ascii converts a hexadecimal data into an ASCII string
>>> bin_to_ascii(b'41')
b'A'
>>> bin_to_ascii(b'54657374696e672e2e2e')
b'Testing...'
"""
# If the length of the binary (or hexadecimal? I'm a little confused as to
# what I'm inputting...) string is an even number, which hasn't
# happened yet with any of my test runs, it should simply convert back to
# ASCII:
# if len(input_binary) % 2 == 0:
# bin_int = int(input_binary, 2)
return binascii.unhexlify(input_binary)
# If not, I try to make the length an even number by adding a '0' to the
# beggining of the string. This is what has been giving me trouble:
# else:
# listog = []
# listog.append('0')
# listog.append(input_binary)
# even_bin = ''.join(listog)
# even_bin_int = int(even_bin, 2)
# return binascii.unhexlify('{0}'.format(even_bin_str))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment