我正在编写一个二进制加法程序,但我不确定为什么当输入以零开始时输出是incorect。当程序必须在其中一个输入的开头添加零时,输出也是错误的它们的长度相同。
a = input('Enter first binary number\t')
b = input('Enter second binary number\t')
carry = 0
answer = ""
length = (max(len(a),len(b))) - min(len(a),len(b))
if b > a:
a = length * '0' + a
elif a > b:
b = length * '0' + b
print(a)
print(b)
for i in range(len(a)-1, -1, -1):
x = carry
if a[i] == '1': x += 1
else: x = 0
if b[i] == '1': x += 1
else: x = 0
if x % 2 == 1: answer = '1' + answer
else: answer = '0' + answer
if x < 2: carry = 0
else: carry = 1
if carry == 1: answer = '1' + answer
print(answer)
答案 0 :(得分:4)
探索布尔逻辑的绝佳机会。
像这样添加二进制文件可以使用两个半加法器来完成#34;和&#34;或&#34;
首先是&#34; Half Adder&#34;这是一个XOR给你一个求和的输出和一个AND来给你一个进位。
[根据评论编辑:python确实将XOR实现为^
但不是&#34;字&#34;例如and
not
or
。我按原样留下答案,因为它正在解释二进制加法后面的布尔逻辑
由于python没有XOR,我们必须编写一个代码。 XOR本身是两个AND(具有反向输入)和OR,如下所示:
这将是一个简单的函数,如下所示:
def xor(bit_a, bit_b):
A1 = bit_a and (not bit_b)
A2 = (not bit_a) and bit_b
return int(A1 or A2)
其他人可能想写如下:
def xor(bit_a, bit_b):
return int(bit_a != bit_b)
这是非常有效的,但我在这里使用布尔示例。
然后我们编码&#34; Half Adder&#34;它有2个输入(bit_a,bit_b)并给出两个输出XOR表示求和和AND表示进位:
def half_adder(bit_a, bit_b):
return (xor(bit_a, bit_b), bit_a and bit_b)
所以两个&#34; Half Adders&#34;和&#34; OR&#34;将制作一个全额加法器&#34;像这样:
如您所见,它将有3个输入(bit_a,bit_b,进位)和2个输出(sum和进位)。这将在python中看起来像这样:
def full_adder(bit_a, bit_b, carry=0):
sum1, carry1 = half_adder(bit_a, bit_b)
sum2, carry2 = half_adder(sum1, carry)
return (sum2, carry1 or carry2)
如果您想将Full Adder视为一个逻辑图,它将如下所示:
然后我们需要调用这个全加器,从最低有效位(LSB)开始,0作为进位,然后按照最高有效位(MSB)的方式运行进位作为输入进入下一步,如此处所示为4位:
这样的结果是这样的:
def binary_string_adder(bits_a, bits_b):
carry = 0
result = ''
for i in range(len(bits_a)-1 , -1, -1):
summ, carry = full_adder(int(bits_a[i]), int(bits_b[i]), carry)
result += str(summ)
result += str(carry)
return result[::-1]
如您所见,我们需要撤消result
字符串,因为我们建立起来了#34;错误的方式&#34;。
将所有内容整合在一起作为完整的工作代码:
# boolean binary string adder
def rjust_lenght(s1, s2, fill='0'):
l1, l2 = len(s1), len(s2)
if l1 > l2:
s2 = s2.rjust(l1, fill)
elif l2 > l1:
s1 = s1.rjust(l2, fill)
return (s1, s2)
def get_input():
bits_a = input('input your first binary string ')
bits_b = input('input your second binary string ')
return rjust_lenght(bits_a, bits_b)
def xor(bit_a, bit_b):
A1 = bit_a and (not bit_b)
A2 = (not bit_a) and bit_b
return int(A1 or A2)
def half_adder(bit_a, bit_b):
return (xor(bit_a, bit_b), bit_a and bit_b)
def full_adder(bit_a, bit_b, carry=0):
sum1, carry1 = half_adder(bit_a, bit_b)
sum2, carry2 = half_adder(sum1, carry)
return (sum2, carry1 or carry2)
def binary_string_adder(bits_a, bits_b):
carry = 0
result = ''
for i in range(len(bits_a)-1 , -1, -1):
summ, carry = full_adder(int(bits_a[i]), int(bits_b[i]), carry)
result += str(summ)
result += str(carry)
return result[::-1]
def main():
bits_a, bits_b = get_input()
print('1st string of bits is : {}, ({})'.format(bits_a, int(bits_a, 2)))
print('2nd string of bits is : {}, ({})'.format(bits_b, int(bits_b, 2)))
result = binary_string_adder(bits_a, bits_b)
print('summarized is : {}, ({})'.format(result, int(result, 2)))
if __name__ == '__main__':
main()
用于图片的两个互联网资源:
为了好玩,你可以用三行来完成,其中两行实际上是输入:
bits_a = input('input your first binary string ')
bits_b = input('input your second binary string ')
print('{0:b}'.format(int(bits_a, 2) + int(bits_b, 2)))
在你自己的代码中,如果在第二次/后续迭代中丢弃一个进位,其中一个位为0,则设置x = 0
,其中包含先前itteration的进位。
答案 1 :(得分:0)
这就是我设法完成这项工作的方法,希望你发现这很有用。
#Binary multiplication program.
def binaryAddition(bin0, bin1):
c = 0
answer = ''
if len(bin0) > len(bin1):
bin1 = (len(bin0) - len(bin1))*"0" + bin1
elif len(bin1) > len(bin0):
bin0 = (len(bin1) - len(bin0))*"0" + bin0
#Goes through the binary strings and tells the computer what the anser should be.
for i in range(len(bin0)-1,-1,-1):
j = bin0[i]
k = bin1[i]
j, k = int(j), int(k)
if k + j + c == 0:
c = 0
answer = '0' + answer
elif k + j + c == 1:
c = 0
answer = '1' + answer
elif k + j + c == 2:
c = 1
answer = '0' + answer
elif k + j + c == 3:
c = 1
answer = '1' + answer
else:
print("There is something wrong. Make sure all the numbers are a '1' or a '0'. Try again.") #One of the numbers is not a 1 or a 0.
main()
return answer
def binaryMultiplication(bin0,bin1):
answer = '0'*8
if len(bin0) > len(bin1):
bin1 = (len(bin0) - len(bin1))*"0" + bin1
elif len(bin1) > len(bin0):
bin0 = (len(bin1) - len(bin0))*"0" + bin0
for i in range(len(bin0)-1,-1,-1):
if bin1[i] == '0':
num = '0'*len(answer)
elif bin1[i] == '1':
num = bin0 + '0'*((len(bin0)-1)-i)
answer = binaryAddition(num, answer)
print(answer)
def main():
try:
bin0, bin1 = input("Input both binary inputs separated by a space.\n").split(" ")
except:
print("Something went wrong. Perhaps there was not a space between you numbers.")
main()
binaryMultiplication(bin0,bin1)
choice = input("Do you want to go again?y/n\n").upper()
if choice == 'Y':
main()
else: input()
main()
答案 2 :(得分:0)
以下内容使用按位逻辑运算符将整数i1和i2相加(i1和i2被覆盖)。它通过i1 xor i2计算按位和,并通过(i1&i2)<< 1计算进位。迭代直到移位寄存器为空。通常,这将比逐位快很多
while i2: # check shift register != 0
i1, i2 = i1^i2, (i1&i2) << 1 # update registers