Binary numbers in Python


How can I add, subtract, and compare binary numbers in Python without converting to decimal?

7/19/2016 1:28:12 PM

Accepted Answer

You can convert between a string representation of the binary using bin() and int()

>>> bin(88)
>>> int('0b1011000', 2)

>>> a=int('01100000', 2)
>>> b=int('00100110', 2)
>>> bin(a & b)
>>> bin(a | b)
>>> bin(a ^ b)
3/3/2015 1:18:42 PM

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow