pythonbinarynegative-numbercomplement

Decimal to binary: two's complement, better expression for negatives


When I give for example: -2 or -8, I get 110, 11000. But I want to get 10, 1000, because it must use the minimum binary numbers. So I have to use another way to the negative ones. I tried to swap 1 and 0 until I reach LSB 1, but I can't find a way.

(To help you: dekadikos = demical, diadikos = binary, boith = assistant)

 dekadikos = input()
 while dekadikos != "end" :
     dekadikos = int(dekadikos)  
     if dekadikos > 0 :
         diadikos = bin(dekadikos)
         diadikos = (diadikos[2:])
         n = int(len(diadikos)) + 1
         print(diadikos.zfill(n))
     elif dekadikos == 0 :
         diadikos = bin(dekadikos)
         diadikos = (diadikos[2:])
         print(diadikos)
     else :
         dekadikos = abs(dekadikos)
         diadikos = bin(dekadikos)
         diadikos = (diadikos[2:])
         n = int(len(diadikos)) + 1
         diadikos = diadikos.zfill(n)
         boithdekadikos = 2**n - dekadikos
         diadikos = bin(boithdekadikos)
         diadikos = diadikos[2:]
         print (diadikos)
 dekadikos = input()

Solution

  • You could solve it by making two changes to your code of the last else block (commented):

    else :
      dekadikos = abs(dekadikos)
      diadikos = bin(dekadikos-1) # subtract 1
      diadikos = (diadikos[2:])
      n = int(len(diadikos)) + (dekadikos>1) # add 1 except for 1
      diadikos = diadikos.zfill(n)
      boithdekadikos = 2**n - dekadikos
      diadikos = bin(boithdekadikos)
      diadikos = diadikos[2:]
      print (diadikos)
    

    It seems like a lengthy method though, to get to your desired result. For one, you could use format(dekadikos, 'b') to get the binary representation of a number without the 0b prefix.

    You could do this instead, which covers positive, zero and negative:

    dekadikos = int(dekadikos)
    diadikos = '0' + format(abs(dekadikos)-(dekadikos<0), 'b')
    if dekadikos == 0:
        diadikos = '0'
    elif dekadikos < 0:
        diadikos = format(2**(len(diadikos)-(dekadikos==-1)) + dekadikos, 'b')
    print (diadikos)