[Tutor] convert binary to ascii
travislspencer at gmail.com
Fri Sep 2 20:09:07 CEST 2005
On 9/2/05, Servando Garcia <servando at mac.com> wrote:
> 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
I don't know about module, but it isn't hard to do it yourself. Here
is one way:
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)
Here is the output of your binary string:
$ python btoa.py <<< "01110011 01100001 01101101"
Its a really common algorithm. Google for "change of base algorithm"
and you'll probably find lots of explinations.
More information about the Tutor