簡體   English   中英

使用簡單的二進制加法器的困難

[英]difficulty with a simple binary adder

我試圖使用python添加2個二進制數字,但我無法弄清楚如何制作一個非常簡單的程序來做到這一點。 這是我到目前為止,但它沒有工作:

b=input("what number would you like to add ")
convert1= lambda b: str(int(b, 2))

a=input("what number would you like to add to it ")
convert= lambda a: str(int(a, 2))

c=(b+a)
print (c)
convert=lambda c: str(int(c, 2))
print ("Your binary numbers added together is" + convert(c))

我的意思是不工作是如果說我嘗試添加1001和1001它會說答案是10011001.這是錯的。

有人可以解釋為什么這不起作用和任何其他簡單的方法這樣做。

沒有“添加二進制”這樣的東西 - 當你添加兩個整數時,它們的基礎是無關緊要的。 整數的基礎只是在文本上表示它時的便利。 因此,您真正想要的是定期添加兩個整數, 然后將結果轉換為二進制(也可能以二進制形式顯示兩個輸入)。 例如:

>>> a = 5  # input 1
>>> b = 3  # input 2
>>> 
>>> bin(a)
'0b101'
>>> bin(b)
'0b11'
>>> 
>>> bin(a + b)
'0b1000'

因為你的ab是字符串,所以c=(b+a)也通過連接ab產生一個字符串。

如果要將輸入讀取為二進制字符串,則可以在執行添加之前將它們簡單地轉換為整數:

>>> a = '101'
>>> b = '011'
>>> 
>>> bin(int(a,2) + int(b,2))
'0b1000'

看起來你要在一起添加兩個字符串; “1001”+“1001”等於“10011001”。

您正在嘗試添加2個字符串! 因此產生連接。

編輯 :似乎您希望輸入也是二進制。

num1 = input("what number would you like to add ")
a = int(num1, 2)

num2 = input("what number would you like to add to it ")
b = int(num2, 2)

ans = bin(a+b)
print("Your addition of numbers, in binary is " + ans)

以上將101總和作為'0b11' 但是,如果你只想打印'11' ,你將不得不使用

ans = bin(a+b)[2:]

只需使用bin(int()) ,請參閱http://docs.python.org/2/library/functions.html#bin

x = raw_input("what number would you like to add ")
print x,'is',bin(int(x)),'in binary'
y=raw_input("what number would you like to add to it ")
print y, 'is',bin(int(y)),'in binary'
print
print 'their sum in binary is',bin(int(x+y))

[OUT]:

$ python test.py
what number would you like to add 123
123 is 0b1111011 in binary
what number would you like to add to it 456
456 is 0b111001000 in binary

their sum in binary is 0b11110001001000000

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM