Dreamy
Dreamy

Reputation: 67

How to get the negative binary number of a positive number

Given a positive number, I am trying to print a string that represents it's negative binary number.

I am doing something like this:

def NegativeBinary(number):

    number_below = number - 1
    bin_number_below = "{0:b}".format(number_below)

    # how can I invert this bin_number_below  afterwards, 
    # so that I return the negative of the number I got as an argument

    return bin_negative_number

In wish I subtract the number given for one, because it's negative binary number is basically the binary representation of number-1, with zeros and ones inverted.

ex :

num = NegativeBinary(5)
print(num)


**** output ****

In[1]:  '1011' 

I am aware of the fact, that since I'm working with strings this might be a bit "trickier", however I'd be very grateful if anyone gave me an ideia on how to do this.

Upvotes: 0

Views: 145

Answers (1)

Mark
Mark

Reputation: 66

You can just do number_below = -number, and it should do what you want it to do. If you subtract one, then you are only subtracting one.

Upvotes: 1

Related Questions