[Tutor] python string __add__

Jeff Shannon jeff@ccvcorp.com
Thu Jun 5 16:43:01 2003


Bob Gailer wrote:

> At 11:00 AM 6/5/2003 -0700, tpc@csua.berkeley.edu wrote:
>
>> I have a script that will take decimal numbers of any length as command
>> line arguments and output the binary equivalent. [...]
>
>
> This program generates Binary Coded Decimal, not Binary. Getting 
> spaces is an effect of the print statement.


Just to expand a bit on what Bob said (he's quite right), this program 
is not going to generate proper binary representations.  As an example, 
the number 13 is '1101' in binary, but your program will represent it as 
'0001 0011'.  It'll be even more confusing after you fix the space 
issue, because binary '00010011' is 19 decimal.

You cannot do a digit-wise conversion of decimal to binary and have it 
work out right.  You *can* do a digit-wise conversion of hexidecimal to 
binary, though -- it works because 16 is a power of 2, but 10 is not. 
 So, if you want a true binary representation of the number, there's two 
approaches.  You'll need to convert your command-line argument to a 
long, either way (Python longs can hold numbers of arbitrary length). 
 Then, you can either start dividing by two and collecting remainders to 
convert that long directly to binary, or you can convert the long into a 
hexidecimal string, chop off the leading '0x', and then use a 
dictionary-based digit-wise conversion (like you're trying to do above).

As Bob mentioned, the spaces that you're getting are coming from print, 
not anything you're doing to the string.  The output of a print 
statement will always end in either a newline or (if a comma is used) a 
space.  There's several alternatives, but the most straightforward is to 
gather each cluster of bits into a single variable.  The easiest way to 
do this is by append()'ing to a list, and then join()'ing that list when 
you're done to get a single string.

Jeff Shannon
Technician/Programmer
Credit International