115

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

A-Tech
  • 806
  • 6
  • 22
  • 3
    Is this a homework question, i.e are you asking how to do maths at a low level? See (http://stackoverflow.com/questions/1149929/how-to-add-two-numbers-without-using-or-or-another-arithmetic-operator/1150996#1150996) – Tom Leys Oct 06 '09 at 03:50
  • 2
    Can you give some examples of what you are trying to achieve? – John La Rooy Oct 06 '09 at 04:17
  • 10
    numbers 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 print – John La Rooy Oct 06 '09 at 04:31

10 Answers10

185

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'
John La Rooy
  • 295,403
  • 53
  • 369
  • 502
  • 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. –  Oct 06 '09 at 12:52
  • 13
    You can also use the binary literal, when using Python 2.6 and above. Instead of `int('01100111',2)` you write `0b01100111` for example, which is `103`. – Joschua Dec 20 '10 at 09:58
10

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
  • 37,580
  • 14
  • 81
  • 100
9

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
  • 57,848
  • 30
  • 97
  • 128
  • 1
    Always fun to write add, sub etc with bitwise operators. For anyone interested in this, look for guides on circuits, more specifically half adders, then full adders and then finally subtractor, maybe even a adder-substractor. From here you can translate it into bitwise operators. – Horse SMith Apr 26 '15 at 03:46
3

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
  • 10,521
  • 4
  • 33
  • 27
0

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:]
Tom Aranda
  • 5,919
  • 11
  • 35
  • 51
  • The digit validation steps are unneeded. It's better to call `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 "", line 1, in > File "", line 2, in addBinary > ValueError: invalid literal for int() with base 2: '113' Similar, but less specific than `AssertionError`s. – Mr. Lance E Sloan May 05 '23 at 15:05
0
'''
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.

GaryMBloom
  • 5,350
  • 1
  • 24
  • 32
  • 2
    You should not post code and 'leave the understanding of it to the reader'. Explain your code so others can understand it quickly. – Yannic Dec 12 '21 at 20:17
-1

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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
-2

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"))
Mona Jalal
  • 34,860
  • 64
  • 239
  • 408
-6

x = x + 1 print(x) a = x + 5 print(a)

frhd
  • 9,396
  • 5
  • 24
  • 41
-8

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.

NathanOliver
  • 171,901
  • 28
  • 288
  • 402
  • 1
    I think you're misinterpreting what the question was asking. OP was looking for a way to read/manipulate numbers in binary representation and have them interact with numbers in an integer representation. – Josh Nov 18 '20 at 16:22