【问题标题】:How to get the negative binary number of a positive number如何获得正数的负二进制数
【发布时间】:2020-09-09 21:17:40
【问题描述】:

给定一个正数,我试图打印一个表示它的负二进制数的字符串。

我正在做这样的事情:

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

希望我减去给定的数字,因为它是负二进制数,基本上是数字 1 的二进制表示,零和一倒置。

前:

num = NegativeBinary(5)
print(num)


**** output ****

In[1]:  '1011' 

我知道这样一个事实,因为我正在使用字符串,这可能有点“棘手”,但是如果有人给我一个关于如何做到这一点的想法,我将非常感激。

【问题讨论】:

  • 您是否假设两个补码以及表示 int 所需的最小字节数?
  • 是的,我想做的是在这种情况下用最少的位数表示负数。有什么想法吗?
  • @Mark 解决方案应该可以工作

标签: python string binary int


【解决方案1】:

你可以做number_below = -number,它应该做你想做的事。如果你减去一个,那么你只是减去一个。

【讨论】:

  • 嗨,马克!我已经尝试过了,但我得到的结果只是前面带有“-”的常规二进制数。例如 x = "{0:b}".format(-5) // x = '-101' ,这不是我想要的
猜你喜欢
  • 1970-01-01
  • 2019-06-03
  • 1970-01-01
  • 2013-07-06
  • 1970-01-01
  • 1970-01-01
  • 2020-02-28
  • 1970-01-01
  • 2023-03-28
相关资源
最近更新 更多