Binary numbers in Python

前端 未结 9 2087
孤独总比滥情好
孤独总比滥情好 2020-12-04 11:14

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

相关标签:
9条回答
  • 2020-12-04 11:49

    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.

    0 讨论(0)
  • 2020-12-04 11:51

    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:]
    
    0 讨论(0)
  • 2020-12-04 11:52
    '''
    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.

    0 讨论(0)
提交回复
热议问题