[Tutor] convert binary to ascii

Travis Spencer travislspencer at gmail.com
Fri Sep 2 20:09:07 CEST 2005


On 9/2/05, Servando Garcia <servando at mac.com> wrote:
> Hello

Hey Servando,

> Here is my question : sam in binary is  01110011  01100001  01101101.
>    if given 01110011  01100001  01101101  how would I go back to ascii.
>   I guess am asking is there a module that will do this conversion for
> me. 

I don't know about module, but it isn't hard to do it yourself.  Here
is one way:

#!/bin/env python

import sys

for line in sys.stdin:
    result = ""

    for binaryStr in line.split():
        j = len(binaryStr) - 1
        i = charCodeOfBinaryStr = 0

        while j > 0:
            charCodeOfBinaryStr += int(binaryStr[j]) * 2 ** i
            j -= 1
            i += 1

        result += chr(charCodeOfBinaryStr)

    print result

Here is the output of your binary string:

$ python btoa.py <<< "01110011  01100001  01101101"
sam

Its a really common algorithm.  Google for "change of base algorithm"
and you'll probably find lots of explinations.

HTH.

-- 

Regards,

Travis Spencer


More information about the Tutor mailing list