简体   繁体   English

如何获得正数的负二进制数

[英]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.希望我减去给定的数字,因为它的负二进制数基本上是数字 1 的二进制表示,零和一倒置。

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.你可以做number_below = -number ,它应该做你想做的事。 If you subtract one, then you are only subtracting one.如果你减去一个,那么你只是减去一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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