How can I add, subtract, and compare binary numbers in Python without converting them to decimal?
-
3Is this a homework question, i.e are you asking how to do maths at a low level? See (stackoverflow.com/questions/1149929/…)Tom Leys– Tom Leys2009-10-06 03:50:26 +00:00Commented Oct 6, 2009 at 3:50
-
2Can you give some examples of what you are trying to achieve?John La Rooy– John La Rooy2009-10-06 04:17:14 +00:00Commented Oct 6, 2009 at 4:17
-
10numbers are already binary in python. They get converted to binary when your program starts and are only converted back to decimal when you use something like str() or printJohn La Rooy– John La Rooy2009-10-06 04:31:04 +00:00Commented Oct 6, 2009 at 4:31
10 Answers
You can convert between a string representation of the binary using bin() and int()
>>> bin(88)
'0b1011000'
>>> int('0b1011000', 2)
88
>>>
>>> a=int('01100000', 2)
>>> b=int('00100110', 2)
>>> bin(a & b)
'0b100000'
>>> bin(a | b)
'0b1100110'
>>> bin(a ^ b)
'0b1000110'
2 Comments
int('01100111',2) you write 0b01100111 for example, which is 103.I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in. The fact that your python interpreter may store things as binary internally doesn't affect how you work with it - if you have an integer type, just use +, -, etc.
If you have strings of binary digits, you'll have to either write your own implementation or convert them using the int(binaryString, 2) function.
Comments
If you're talking about bitwise operators, then you're after:
~ Not
^ XOR
| Or
& And
Otherwise, binary numbers work exactly the same as decimal numbers, because numbers are numbers, no matter how you look at them. The only difference between decimal and binary is how we represent that data when we are looking at it.
1 Comment
Below is a re-write of a previously posted function:
def addBinary(a, b): # Example: a = '11' + b =' 100' returns as '111'.
for ch in a: assert ch in {'0','1'}, 'bad digit: ' + ch
for ch in b: assert ch in {'0','1'}, 'bad digit: ' + ch
sumx = int(a, 2) + int(b, 2)
return bin(sumx)[2:]
1 Comment
int(a, 2) immediately & handle ValueError exception(s) that are thrown if value(s) are invalid binary. Or leave out exception handling & let them be raised. If validation steps are removed from your code & we call addBinary('113', '100'), the result is… > Traceback (most recent call last): > File "<stdin>", line 1, in <module> > File "<stdin>", line 2, in addBinary > ValueError: invalid literal for int() with base 2: '113' Similar, but less specific than AssertionErrors.'''
I expect the intent behind this assignment was to work in binary string format.
This is absolutely doable.
'''
def compare(bin1, bin2):
return bin1.lstrip('0') == bin2.lstrip('0')
def add(bin1, bin2):
result = ''
blen = max((len(bin1), len(bin2))) + 1
bin1, bin2 = bin1.zfill(blen), bin2.zfill(blen)
carry_s = '0'
for b1, b2 in list(zip(bin1, bin2))[::-1]:
count = (carry_s, b1, b2).count('1')
carry_s = '1' if count >= 2 else '0'
result += '1' if count % 2 else '0'
return result[::-1]
if __name__ == '__main__':
print(add('101', '100'))
I leave the subtraction func as an exercise for the reader.
1 Comment
For example, 00000011 - 00000001 = 00000010
You can remove the zeroes and then add them again after you do your calculation! This works very easy.
If your binary is stored as a string then you can convert to int which will automatically strip the zeroes from the start. After you have your answer you can turn it back into a string and add the zeroes to the start.
Comments
Not sure if helpful, but I leave my solution here:
class Solution:
# @param A : string
# @param B : string
# @return a strings
def addBinary(self, A, B):
num1 = bin(int(A, 2))
num2 = bin(int(B, 2))
bin_str = bin(int(num1, 2)+int(num2, 2))
b_index = bin_str.index('b')
return bin_str[b_index+1:]
s = Solution()
print(s.addBinary("11", "100"))
Comments
I think you're confused about what binary is. Binary and decimal are just different representations of a number - e.g. 101 base 2 and 5 base 10 are the same number. The operations add, subtract, and compare operate on numbers - 101 base 2 == 5 base 10 and addition is the same logical operation no matter what base you're working in.