Switching a value from positive to negative using binary and twos complement

59 views Asked by At

So for my college computing course(UK), we were assigned a homework task to change a user's input to its negative equivalent (1 to -1, 13 to -13 etc...) but I cant figure out how to do it. I've got some code I've smashed together from other pages on stackoverflow, but my outputted result always includes a 0 on the front, meaning the value isn't negative anymore. I'm unsure how to change this as when i alter my recursive code at the bottom, I get the error of:

File "<ipython-input-23-300b7347f10c>", line 22
    return(num % 2, end = '')
                    ^
SyntaxError: invalid syntax. Maybe you meant '==' or ':=' instead of '='?

I'm reasonably new to coding seriously, only having focused on basics back in high school so I don't really know how to solve this issue.

(Also, we were told we couldn't use any of python's inbuilt functions for converting to and from binary and denary)

#Outputting original binary
binary = str(input("Enter a binary number:")) #asks for the binary number
RevBinary =binary[::-1] #Reverses the number for multiplying
count = 0 #sets counter at 0
denary = 0 #sets the denary value at 0


for number in RevBinary:
  denary += 2**count*int(number) #does 2^count multiplied by whatever the number in RevBinary the for loop is currently at
  count+=1 #increases count for next number

print("The original denary number is: [", denary, "]")

#----THE PROBLEM AREA----
NewDenary = Denary + 1 

def DecimalToBinary(num):

  if num >= 1:
    DecimalToBinary(num // 2)
  print(num % 2, end = '') ####Can't edit this line else i get the error message stated above

DecimalToBinary(NewDenary)
1

There are 1 answers

1
SmellyCat On

It looks to me like the return statement was just a mis-pasting. If you want to build a string by recursion, you just need a plus sign between strings.

def decimal_to_binary(num:int):
    if num < 0:
        raise ValueError('negative numbers not supported')
    elif num > 1:
        return decimal_to_binary(num >> 1) + decimal_to_binary(num & 1)
    else:
        return '1' if (num & 1) else '0'

Flipping bits in a string of ones and zeros sounds like a simple list-comprehension and a string join, maybe with some padding. I'm reluctant to post what sounds like a full solution to an assignment.