[Tutor] Negative Signed Binary Conversion

Eric Brunson brunson at brunson.com
Mon Oct 22 20:09:27 CEST 2007


Why not find the sign, calculate the binary of the absolute value, then 
make the result negative (twos complement) if necessary?

Just a thought.

ddm2 at sfu.ca wrote:
> Hi,
> I'm trying to get this binary converter working, but I can't seem to get the
> negatives to work properly. If the integer is too low, the 0's that are
> added for the amount of bits gets out of whack. I've tried to solve the
> problem by adding another 'count' meter by which I can then tell if there
> are too many 0's, but it hasn't worked at all.
> CODE:
> def conversion(n):
>     b = ''
>     while n > 0:
> 	r = n%2
> 	n = n/2
> 	r = str(r)	
> 	b = r+b 	
>     return b	
>
> def positive(n,bits,count):
>     append_zeros = bits - count
>     if append_zeros > 0:
> 	return "0" + (append_zeros-1)*"0" + conversion(n)
>
> def negative(n,bits,count,new_count):
>     n = abs(n)
>     append_zeros = bits - count
>     while new_count > bits and new_count < bits-count:
> 	append_zeros = append_zeros - 2
> 	continue
>     if append_zeros > 0:
> 	return "1" + (append_zeros-6)*"0" + conversion(n)
>
> def signed_mag():
>     print ""
>     print "--------------------"
>     print "Signed Binary"
>     print "--------------------"
>     print ""
>     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")
>     new_count = 0
>     new_count = negative(n,bits,count,new_count).count("0") \
> 		+ negative(n,bits,count,new_count).count("1")
>     if bits - 1 < count:
> 	print "Out of range."
>     else:
> 	if n < 0:
> 	    print n,"is encoded as", negative(n,bits,count,new_count), \
> 		  "in Signed Binary."		
> 	elif n > 0:
> 	    print n,"is encoded as", positive(n,bits,count), \
> 		  "in Signed Binary."
> 	else:
> 	    print "That is not an valid signed interger."
>
> Any help will be greatly appreciated. Thanks in advance.
>
> Cheers,
> Devon
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>   



More information about the Tutor mailing list