Search code examples
pythonlogic

Pythonic way to do logic operations on binary numbers with n number of inputs


I'm coding a digital logic program in python, and am interested in a best practice way to do logical operations on binary numbers. Ideally I'd like to compare bits from an arbitrary number of inputs, eg - [1011, 0101, 1001], etc- and compute a result.

Here are some attempts to AND a couple of 8bit words. In only the second attempt, am I able to compare more than two binary numbers, but this approach just looks bad to me. I don't really care if the binary number is originally represented as a string or as an integer (in each attempt here I need to do some conversion to another type anyway). As mentioned, I'd like to find a pythonic way to do this.

Anyway, here are my clumsy first attempts... ;)

# Attempt 1 - compute result for each bit/element in string, and create a new string

# inputs
a = '10100001'
b = '10101101'

bits = 8

result = ''
for i in range(bits):
    new_bit = int(a[i]) & int(b[i])
    result = result[:i] + str(new_bit) + result[i:]

print result



# Attempt 2  - for each bit in each input, check if 0 or 1.. if 0, the new_bit is 0, otherwise, the new_bit = 0

inputs = ['11000001', '11001011', '11101101']

bits = 8

result = ''
for i in range(bits):
    new_bit = '1'
    for iput in inputs:
        if iput[i] == '0':
             new_bit = '0'
     
    result = result[:i] + str(new_bit) + result[i:]

print result



# Attempt 3 - 

bits = 8

# inputs
a = int('00001001', 2)   
b = int('00001101', 2)  

result = bin(a & b).split('0b', 1)[1].zfill(8) 

print result

Just on brevity, I'm tending towards something like the 3rd attempt, but not quite sure how to handle this for something with more than two inputs.

Any advice would be very appreciated, thankyou.


Solution

  • Use reduce() to perform a repeated operation on all elements of a list.

    from functools import reduce
    
    inputs = ['11000001', '11001011', '11101101']
    inputs = [int(i, 2) for i in inputs] # Convert from binary string to number
    
    result = reduce(lambda x, y: x & y, inputs) # combine them with AND
    print(f"{result:08b}") # print result as 8-bit binary with leading zeroes