| by Arround The Web | No comments

Bitwise AND Operator in Python

Operators play a very important and crucial role since the day they were defined and used in programming languages. Each programming language allows the user to use the Bitwise operators to achieve their implementation goal. Bitwise operators perform well with any kind of formula, built-in, or user-defined functions. The operators are special symbols that perform the logical and arithmetic operations on values and variables. The values or variables which are used to perform the operations using the operators are commonly known as “operators”. This article is about this concept.

What Are the Bitwise Operators in Python?

The Bitwise operators in Python are used to perform the Bitwise calculations on variables, numbers, or integers. First, the integers, or numbers are converted into binary. Then, a Bitwise operation is performed with Bitwise operators on the converted integers bit by bit. This is why it is called Bitwise operations. The result produced by the Bitwise operation is given in decimal format. The point to note here is that the Bitwise operators in Python only work with integers. Following is the list of Bitwise operators defined in Python’s standard library.

Name Operator sign Syntax Output
Bitwise OR | a|b Returns 1 only when both variables are 1 else 0.
Bitwise AND & a&b Returns 0 only when both variables are 0 else 1.
Bitwise NOT ~ ~a Returns the complement of the number.
Bitwise XOR ^ a^b Returns 1 when both bits are different else 0.
Bitwise right shift >> a>> Shifts the bits to the right.
Bitwise left shift << a<< Shifts the bits to the left.

In this tutorial, we will only focus on the Bitwise AND operator and implement some easy, simple, and relevant examples to completely understand the operation of the AND operator. The Bitwise AND takes two variables or decimal numbers as input, convert them into binary, applies the AND operation, and returns the decimal number.

Example 1:

So far, we discussed the syntax and basic function of the AND operator. Now is the time to explore some example code to learn how to implement the AND Bitwise function in the Python code. First, let us see the following code. Then, we explore each statement one by one.

Here, two variables are defined: x = 11 and y = 6. A Bitwise operator converts each decimal number into a binary number before applying a Bitwise AND operation. We show what is 11 in binary and what is 6 in binary. After that, we apply the Bitwise AND operator on x and y and generate the output.

= 11

= 6

print(x," converted in binary ",format(x,"b"))

print(y," converted in binary ",format(y,"b"))

print("The bitwise & of ",x," AND ", y, " is: ",x & y )

The previous illustration is the output given by the Bitwise AND operator. When 11 is converted into binary, it gives 1011. When 6 is converted into binary, it gives 0110. The Bitwise AND is applied to both binary numbers 1011 & 0110 which results to 0010 which is 2 in decimal representation.

Example 2:

In this example, we are going to see the difference between the AND and & operator in Python. The “AND” operator in Python is a logical AND that returns “FALSE” or “0” for each case except when both bits are “TRUE” or “1”. On the other hand, the “&” operator is used to represent the Bitwise operation that primarily works with bits and performs the bit-by-bit operations. Now, let us code something to understand the difference in the functioning of the “AND” and “&” operators.

= 11

= 6

print(x," AND ", y," = ",and y)

print(x," & ", y," = ",x & y)

Let us see the following output. As you might notice, “AND” returns 6 while “&” returns 2. This is because when the “AND” operator is applied to x and y, it checks whether x and y are logically TRUE. However, when we apply the “&” operator, it performs the Bitwise “AND” operation and provides the calculated result. For the “AND” operation, the compiler examines the first variable. If it returns “TRUE”, it checks the second variable. Otherwise, it simply returns “FALSE”.

As a matter of fact, AND only returns “TRUE” when both variables are “TRUE”. Otherwise, it always returns “FALSE”. Hence, when the compiler finds “FALSE” at the beginning, it does not have to check the next variable. Since it does not matter whether the second variable is “TRUE” or “FALSE”, it immediately returns “FALSE”. This whole scenario is commonly known as “Lazy Evaluation” since the compiler does not go further once it gets a “FALSE”.

Example 3:

In this example, we will explore the operator overloading. The concept of operator overloading is that it gives an extended meaning to the predefined operational meaning of the operators. For example, the + operator is used to take the sum of two numbers. However, it is also used to merge two lists or join two strings together. This happens because the + operator is overloaded by the “str” class and “int” class. Hence, when an operator shows a different behavior other than its default behavior, it is considered an operator overloading. Let us see an example of the Bitwise AND operator overloading.

class AND():
    def __init__(self, value):
        self.value = value
    def __and__(self, obj):
        print("Bitwise And operator overloaded")
        if isinstance(obj, AND):
            return self.value & obj.value
        else:
            raise ValueError("Should be an object of class AND")
if __name__ == "__main__":
    x = AND(10)
    y = AND(12)
    print("x & y = ",x & y)

The output of the operator overloading example is given in the following illustration:

Conclusion

This article provides a quick overview of the Bitwise AND operation. We have seen the basic definition of the different Bitwise operators given in the Python’s standard library. However, we mainly focused on the concept of the Bitwise AND operator. The AND operator takes two decimals as input parameters, converts them into a binary number, performs a Bitwise AND operation on it, converts the binary result into decimal, and returns the output in decimal format. Some simple and useful examples are provided to have a clear understanding of what the Bitwise AND operator do and how it works. Practice these examples so you can easily use them in your Python programs.

Share Button

Source: linuxhint.com

Leave a Reply