[Tutor] convert ascii to binary

Steven D'Aprano steve at pearwood.info
Wed Sep 12 14:38:50 CEST 2012


On 12/09/12 21:20, Aaron Pilgrim wrote:
> Hello,
> I am trying to write a small program that converts ascii to binary.


Can you explain what you mean by "ascii to binary"? Any of these
could be described that way:

'hello world'

=> '68656c6c6f20776f726c64'
=> 'begin 666 <data>\n+:&5L;&\\@=V]R;&0 \n \nend\n'
=> 'aGVsbG8gd29ybGQ=\n'
=> 'x\x9c\xcbH\xcd\xc9\xc9W(\xcf/\xcaI\x01\x00\x1a\x0b\x04]'

or many others.

For the record, those are:

* raw hex string
* uuencode
* base64
* zip compressed[1]


Reading ahead, I think you want the raw hex string, correct?


> I tried using the python reference library section 18.8 but had
> trouble understanding how to make it work.
>
>   Here is the code I am currently trying to use:
>
> def main():	
> 	import binascii

As a general rule, imports should go in the top-level of the module,
not inside the body of a function. There are exceptions to that
rule, but in this case there is no reason not to follow it. So:


import binascii

def main():
     # body of main without the import


> 	myWord = input("Enter the word to convert..")	
> 	#convert text to ascii
> 	for ch in myWord:
> 		print(ord(ch))		
> 		#convert ascii to binary
> 		binascii.a2b_uu(ord(ch))


There is no need to process the string one character at a time.
Try this instead:


import binascii

def main():
     line = input("Enter a line of text to convert: ")
     print(binascii.hexlify(line))


If you want to do it one character at a time, there's no need
for binhex:



def main():
     line = input("Enter a line of text to convert: ")
     for c in line:
         print("Char: '%c'  Ord: %3d (decimal) %x (hex)" % (c, ord(c), ord(c)))






[1] It is ironic that zip compression on a short string leads
to a *longer* string


-- 
Steven



More information about the Tutor mailing list