Bitwise AND Operation Between Binary Strings in Python

In this programming example, we take two binary strings and compute bitwise AND operation between the strings using Python. If the given strings are unequal in length then we first make them equal by prepending 0s in the string with lesser length.

Python Source Code

# bitwise AND operation between two binary strings in python

def make_string_equal_length(a, b):
    len1 = len(a)
    len2 = len(b)

    if len1 > len2:
        b = "0" * (len1 - len2) + b
        a = "0" * (len2 - len1) + a
    return a, b

def bitwise_and(string1, string2):
    str1, str2 = make_string_equal_length(string1, string2)
    result = ''
    for a_bit, b_bit in zip(str1, str2):
        if a_bit == "1" and b_bit == "1":
            result += "1"
            result += "0"
    return result


The output of the above program is: