简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM