Reputation: 13
I am trying to add 2 binary numbers together using python but i can not figure out how to make a very simple program to do it. This is what i got so far but it is not working:
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))
What i mean by not working is if say i try adding 1001 and 1001 it will say the answer is 10011001. Which is wrong.
Can someone please explain why this is not working and any other simple ways of doing this.
Upvotes: 0
Views: 1911
Reputation: 1
It looks like you are adding two strings together; "1001" + "1001" does equal "10011001".
Upvotes: 0
Reputation: 122082
Just use bin(int())
, see 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
Upvotes: 0
Reputation: 13372
You are trying to add 2 strings! Hence the resultant concatenation.
Edit: Seems that you want the input to be in binary too.
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)
The above would give sum of 10
& 1
as '0b11'
. But, if you want to only print '11'
, you would have to use
ans = bin(a+b)[2:]
Upvotes: 0
Reputation: 129517
There is no such thing as "adding in binary" -- when you add two integers, their base is irrelevant. An integer's base is only a convenience when representing it textually. Therefore, what you really want is to add the two integers regularly and then convert that result to binary (and perhaps display the two inputs in binary as well). For instance:
>>> a = 5 # input 1
>>> b = 3 # input 2
>>>
>>> bin(a)
'0b101'
>>> bin(b)
'0b11'
>>>
>>> bin(a + b)
'0b1000'
As is, your a
and b
are strings, so c=(b+a)
also produces a string by concatenating a
and b
.
If you want to read your inputs as binary strings, then you can simply convert them to integers before performing the addition:
>>> a = '101'
>>> b = '011'
>>>
>>> bin(int(a,2) + int(b,2))
'0b1000'
Upvotes: 2