Morten Amundsen Morten Amundsen - 1 year ago 172
Python Question

Converting Binary to ASCII, and ASCII to Binary

I'm currently writing an ascii-binary/binary-ascii converter in Python for a school project, and I have an issue with converting from ascii (String text) to binary. The idea is to print the outcome in the test() on the bottom of the code.

When running the code in WingIDE, an error occurs:
On the line starting with

bnary = bnary + binary[chnk]

KeyError: "Norway stun Poland 30:28 and spoil Bielecki's birthday party."

What I'm trying to do here is to convert the String of text stored in "text.txt" to a String of integers, and then print this binary string.

Any help is greatly appreciated. I tried looking at other ascii-binary vice-versa convertion related questions, but none seemed to work for me.

My code:

def code():
binary = {}
ascii = {}

# Generate ascii code
for i in range(0,128) :
ascii[format(i,'08b')] = chr(i)

# Reverse the ascii code, this will be binary
for k, v in ascii.iteritems():
binary[v] = binary.get(v, [])

return ascii

def encode(text,binary):
Encode some text using text from a source
bnary = ""

fi = open(text, mode='rb')
while True:
chnk =
if chnk == '':
if chnk != '\n':

binry = ""

bnary = bnary + binary[chnk]

return bnary

def decode(sourcecode,n, ascii):
Decode a sourcecode using chunks of size n

sentence = ""

f = open(sourcecode, mode='rb') # Open a file with filename <sourcecode>
while True:
chunk = # Read n characters at time from an open file
if chunk == '': # This is one way to check for the End Of File in Python
if chunk != '\n':

setence = "" # The ascii sentence generated

# create a sentence
sentence = sentence + ascii[chunk]

return sentence

def test():
A placeholder for some test cases.
It is recommended that you use some existing framework, like unittest,
but for a temporary testing in a development version can be done
directly in the module.

print encode('text.txt', code())
print decode('sourcecode.txt', 8, code())


Answer Source

If you want to decode and encode, have this solutions

Encode ascii to bin

def toBinary(string):
    return "".join([format(ord(char),'#010b')[2:] for char in string])

Encode bin to ascii

def toString(binaryString)
    return = "".join([chr(int(binaryString[i:i+8],2)) for i in range(0,len(binaryString),8)])