[Tutor] Negative Signed Binary Conversion

Alan Gauld alan.gauld at btinternet.com
Tue Oct 23 00:44:08 CEST 2007


<ddm2 at sfu.ca> wrote

> I'm trying to get this binary converter working, but I can't seem to 
> get the
> negatives to work properly.

I already sent a reply on this, but:

> def conversion(n):
>    b = ''
>    while n > 0:

This line means you only ever return an empty string for a negative 
n...

>    n = int(raw_input("Please enter a signed integer: "))
>    bits = int(raw_input("Please enter the number of bits: "))
>    count = conversion(n).count("0") + conversion(n).count("1")

And you call it with anegative n here and use the empty
string to calculate the count... => 0.

HTH,


-- 
Alan Gauld
Author of the Learn to Program web site
http://www.freenetpages.co.uk/hp/alan.gauld 




More information about the Tutor mailing list