Reputation: 21
I am trying to write a function that adds two binary numbers without conversion. My codes are as following, I don't know why it doesn't work.
def add_bitwise(s1, s2):
"""take two strings s1 and s2 that represent binary numbers,
compute the sum of the numbers, and return that sum in the form of a string
that represents a binary number
"""
if s1 == "":
return s2
elif s2 == "":
return s1
else:
rest = add_bitwise(s1[:-1], s2[:-1])
if int(s1[-1]) + int(s2[-1]) == 0:
return rest + "0"
elif int(s1[-1]) + int(s2[-1]) == 1:
return rest + "1"
return add_bitwise(s1[:-1], str(int(s2[:-1])+1)) + str(int(s1[-1]) + int(s2[-1]) - 2)
So I am trying to use a right-to-left approach. If both of the last numbers of s1 and s2 are "0"s, the function returns "0" and continues; if one of the last number of s1 or s2 is "1" while the other last number is "0", the function returns "1" and continues. The part that is not working is when both last numbers are "0"s, that is, a situation when a carry bit is needed.
Upvotes: 0
Views: 503
Reputation: 395793
I would construct the function like this.
def add_bitwise(s1, s2):
return bin(int(s1, 2) + int(s2, 2))
It converts the strings from base 2 into integers, adds them together, and returns the binary string representation again.
Usage:
add_bitwise('10101010', '1010101')
returns
'0b11111111'
Upvotes: 1