用Python编写16位二进制正数的二元补码

2024-06-26 11:03:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我知道有两种方法可以做到这一点,但我对其中至少一种在python中工作的编程感到不安。你知道吗

第一种方法: 循环所有数字,如果是0,则将其更改为1,如果是1,则将其更改为0。这是一的补充。这不是问题。 然后在最右边的二进制位上加1个基2,生成二者的补码。这个方法的问题是,如果需要携带1,那么在整个位相加时携带1。你知道吗

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

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

在python中将方法实现到程序中所遇到的复杂问题是,一旦读取了1,我就有一个增加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  

Tags: the方法inforifbitorder数字
1条回答
网友
1楼 · 发布于 2024-06-26 11:03:22

你的想法是对的。在这个解决方案中,我们首先得到1的补码,然后按照您的期望将1加到结果中。需要注意的是,在二进制数中加一是相对容易的(即使是在字符串表示中)。你知道吗

关键是要跟踪运送。一旦你把“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'

如期而至

相关问题 更多 >