Binary numbers in Python

Question:

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

Asked By: EkSwaim

||

Answers:

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.

Answered By: Pierre Bourdon

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.

Answered By: Steven Schlansker

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.

Answered By: Smashery

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'
Answered By: John La Rooy

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.

Answered By: user5554869

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"))
Answered By: Mona Jalal

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:]
Answered By: mastueben

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

Answered By: user9491697
'''
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.

Answered By: Gary02127

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.

Answered By: Mr Keprins
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.