tags:

views:

583

answers:

4

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

+1  A: 

Binary, decimal, hexadecimal... the base only matters when reading or outputting numbers, adding binary numbers is just the same as adding decimal number : it is just a matter of representation.

Pierre Bourdon
+5  A: 

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.

Steven Schlansker
A: 

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.

Smashery
+2  A: 

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'
gnibbler
Thank you. Yes, this is a homework assignment. The assignment states that I am supposed to leave the numbers in 'binary format' when performing ._add, ._sub, ._gt, ._lt, and ._eq. Your example above seems to convert from bin to int. I am not sure if this will be acceptable but I don't see any other way it could be except your example.
EkSwaim