Python Forum

Full Version: Simple text to binary python script
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi all,

super new to python and working on a text to binary convertor using a dictionary, and wanting to understand how I get back to text after I have the binary output.

I currently have this;
def to_text_code(text):
    code = {'a':'01100001','b':'01100010','c':'01100011}

    text_code = ""

    for x in text:
        text_code += code[x.lower()]
    return text_code

text = input("Text to Binary Converter: ")
print(to_text_code(text))
It seems to work for the letters that I have placed in my dictionary and I can have multiple entries. However, when reversing the dictionary to go from binary back to text I'm having lots of issues.

Any help would be great,

thanks,

G
What exactly is your problem? Having difficulties of splitting an array of bits into bytes? Try this:
sub split_bitrange_in_bytes(string_with_bits)
    for bitcounter in range(0, len(string_with_bits), 8):
        print(string_with_bits[bitcounter:bitcounter + 8])
(Feb-04-2020, 07:00 PM)ibreeden Wrote: [ -> ]However, when reversing the dictionary to go from binary back to text I'm having lots of issues.
You really don't need to make this dictionary(a lot of job for all characters Doh) as Python has tool build in for convert.
When you have the dictionary can look at doing it both ways as a exercise.
def to_text_code(text):
    code = {
        "a": "01100001",
        "b": "01100010",
        "c": "01100011",
    }
    if text.isalpha():
        return code.get(text, f'No record for <{text}>')
    else:
        rev = {v: k for k, v in code.items()}
        return rev.get(text, f'No record for <{text}>')

lst = ['a', '01100001', 'b', "01100010"]
for text in lst:
    print(to_text_code(text)
Output:
01100001 a 01100010 b
Convert back and forth,can try to make function using this.
>>> c = 'a'
>>> c = f"{ord(c):08b}"
>>> c
'01100001'
>>> 
>>> chr(int(c, 2))
'a'