首页 > 解决方案 > 在 Python 中编写正 16 位二进制数的二进制补码

问题描述

我必须只使用循环,而不是任何特殊的内置 python 库函数。假设输入是 0000000000000110,我想要的输出是 1111111111111001。

我知道这样做的两种方法,但我在编程时遇到了麻烦,至少其中一种在 python 中工作。

第一种方法: 遍历所有数字,如果是0则将其更改为1,如果是1则将其更改为0。这是一个的补码。这不是问题。然后将 1 base 2 添加到最右边的二进制位,并生成二进制补码。如果需要携带 1,则在添加整个位时,我使用此方法遇到的问题是携带 1。

第二种方法(可能更简单): 从最右边的位开始循环遍历二进制数。在读取第一个 1 之前,不要反转数字。读取 1 后,不要反转第一个 1。而是反转读取的第一个 1 左侧的所有位(请记住,我从最右边的位开始循环遍历数字)。

简单的 8 位示例) 00000110 循环从最右边的位开始的数字 0(与原始无变化) 1(与原始无变化) 0(与原始相反) 1(与原始相反) 1(与原始相反) 1(从原始反转)1(从原始反转)1(从原始反转)

我在 python 中将方法实现到程序中时遇到的复杂情况是,一旦读取 1,我的计数器就会增加一。所以我说如果 i == 0 或 i == 1:如果 i > 1 则不要反转:反转

但是,您可以从我在下面给出的示例中看到一个小问题。例如)1101 1 0 问题:(i 仍然等于 1)0 0

当我想得到:1101 1 1 0 0

#second method
#input is a string
def twosComp(num) :
  pile = ""
  pile2 = ""
  pile3 = ""
  i = 0

  #reverses the order of the bits(i.e. first bit in num is the last bit in 
  #pile) 
  for bit in num :
    pile = bit + pile
  print pile

 #SUPPOSED TO DO THE TWO'S COMPLEMENT (BUT THE I COUNTER CAUSES A PROBLEM)
  for bit in pile :
   if bit == "1" :
     i += 1
   if i == 0 or i == 1 :
     if bit == "0" :
       pile2 = pile2 + "0"
     elif bit == "1" :
       pile2 = pile2 + "1"
   elif i > 1 :
     if bit == "0" :
       pile2 = pile2 + "1"
     elif bit == "1" :
       pile2 = pile2 + "0"

   #reverses the order of the bits back to the correct order
   for bit in pile2 :
     pile3 = bit + pile3
   print pile3
   #>>> twosComp("1101")
   #1011
   #0001
   #pile3 the last output should be 0011


#method 1
def twosCompMOne(num) :
   pile = ""
   pile2 = ""
   pile3 = ""

   #reverses the order of the bits 
   for bit in num :
     pile = bit + pile
   print pile

  #inverts all the bits in pile
  for bit in pile :
    if bit == "0" :
      pile2 = pile2 + "1"
    if bit == "1" :
      pile2 = pile2 + "0"

  #reverses the order of the bits back to the correct order
  for bit in pile2 :
    pile3 = bit + pile3
  print pile3
  #Now I don't know how to do the add 1 carrying by looping  

标签: python

解决方案


你的总体思路是对的。在这个解决方案中,首先我们得到一个的补码,然后我们按照您的期望将一个添加到结果中。需要注意的是,向二进制数加一相对容易(即使在字符串表示中也是如此)。

关键是跟踪进位。只要将“1”添加到“0”,您就不必再携带了。我们将坚持基本步骤,而不是使用花哨的算法。

def invert(bin_string):
    """string -> string
    return the string representation of inverting every bit of a binary number
    represented by `bin_string`
    """
    return "".join("0" if i == "1" else "1" for i in bin_string)

现在是实际的 2 的补码

def twos_comp(bin_string):
    """string -> string
    return a string representing the 2's complement of `bin_string`
    """
    addendum = 1
    res = ""
    for i in invert(string)[::-1]:
        if not addendum:
            res = i + res
        elif i == "0":
            res = "1" + res
            addendum = 0
        else:
            res = "0" + res
    return res

有了这个定义:

>>> twos_comp("1101")
'0011'
>>> twos_comp("110110")
'001010'

正如预期的那样


推荐阅读