Open In App

Python Bitwise Operators

Last Updated : 21 May, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic and logical computations. The value the operator operates on is known as the Operand. 

Python Bitwise Operators

Python bitwise operators are used to perform bitwise calculations on integers. The integers are first converted into binary and then operations are performed on each bit or corresponding pair of bits, hence the name bitwise operators. The result is then returned in decimal format.

Note: Python bitwise operators work only on integers.


OPERATOR   NAMEDESCRIPTIONSYNTAX

Bitwise AND operator

&Bitwise ANDResult bit 1, if both operand bits are 1; otherwise results bit 0.x & y

Bitwise OR operator

|Bitwise ORResult bit 1, if any of the operand bit is 1; otherwise results bit 0.x | y

Bitwise XOR Operator

^Bitwise XORResult bit 1, if any of the operand bit is 1 but not both, otherwise results bit 0.x ^ y

Bitwise NOT Operator

~Bitwise NOT

Inverts individual bits.

~x

Python Bitwise Right Shift

>>Bitwise right shift

The left operand’s value is moved toward right by the number of bits 

specified by the right operand.

x>>

Python Bitwise Left Shift

<<Bitwise left shift

The left operand’s value is moved toward left by the number of bits 

specified by the right operand.

x<<

Let’s understand each operator one by one.

Bitwise AND Operator

The Python Bitwise AND (&) operator takes two equal-length bit patterns as parameters. The two-bit integers are compared. If the bits in the compared positions of the bit patterns are 1, then the resulting bit is 1. If not, it is 0.

Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of both X & y

Note: Here, (111)2 represent binary number.

Python
a = 10
b = 4

# Print bitwise AND operation
print("a & b =", a & b)

Output

a & b = 0

Bitwise OR Operator

The Python Bitwise OR (|) Operator takes two equivalent length bit designs as boundaries; if the two bits in the looked-at position are 0, the next bit is zero. If not, it is 1.

Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise OR of both X, Y

Python
a = 10
b = 4

# Print bitwise OR operation
print("a | b =", a | b)

Output

a | b = 14

Bitwise XOR Operator

The Python Bitwise XOR (^) Operator also known as the exclusive OR operator, is used to perform the XOR operation on two operands. XOR stands for “exclusive or”, and it returns true if and only if exactly one of the operands is true. In the context of bitwise operations, it compares corresponding bits of two operands. If the bits are different, it returns 1; otherwise, it returns 0.

Example: Take two bit values X and Y, where X = 7= (111)2 and Y = 4 = (100)2 . Take Bitwise and of both X & Y

Python
a = 10
b = 4

# print bitwise XOR operation
print("a ^ b =", a ^ b)

Output

a ^ b = 14

Bitwise NOT Operator

The preceding three bitwise operators are binary operators, necessitating two operands to function. However, unlike the others, this operator operates with only one operand.

The Python Bitwise Not (~) Operator works with a single value and returns its one’s complement. This means it toggles all bits in the value, transforming 0 bits to 1 and 1 bits to 0, resulting in the one’s complement of the binary number.

Example: Take two bit values X and Y, where X = 5= (101)2 . Take Bitwise NOT of X.

Python
a = 10
b = 4

# Print bitwise NOT operation
print("~a =", ~a)

Output

~a = -11

Bitwise Shift

These operators are used to shift the bits of a number left or right thereby multiplying or dividing the number by two respectively. They can be used when we have to multiply or divide a number by two. 

Python Bitwise Right Shift

Shifts the bits of the number to the right and fills 0 on voids left( fills 1 in the case of a negative number) as a result. Similar effect as of dividing the number with some power of two.

Example 1:
a = 10 = 0000 1010 (Binary)
a >> 1 = 0000 0101 = 5

Example 2:
a = -10 = 1111 0110 (Binary)
a >> 1 = 1111 1011 = -5 
Python
a = 10
b = -10

# print bitwise right shift operator
print("a >> 1 =", a >> 1)
print("b >> 1 =", b >> 1)

Output

a >> 1 = 5
b >> 1 = -5

Python Bitwise Left Shift

Shifts the bits of the number to the left and fills 0 on voids right as a result. Similar effect as of multiplying the number with some power of two.

Example 1:
a = 5 = 0000 0101 (Binary)
a << 1 = 0000 1010 = 10
a << 2 = 0001 0100 = 20 

Example 2:
b = -10 = 1111 0110 (Binary)
b << 1 = 1110 1100 = -20
b << 2 = 1101 1000 = -40 
Python
a = 5
b = -10

# print bitwise left shift operator
print("a << 1 =", a << 1)
print("b << 1 =", b << 1)

Output: 

a << 1 = 10
b << 1 = -20

Bitwise Operator Overloading

Operator Overloading means giving extended meaning beyond their predefined operational meaning. For example operator + is used to add two integers as well as join two strings and merge two lists. It is achievable because the ‘+’ operator is overloaded by int class and str class. You might have noticed that the same built-in operator or function shows different behavior for objects of different classes, this is called Operator Overloading.

Below is a simple example of Bitwise operator overloading.

Python
# Python program to demonstrate
# operator overloading


class Geek():
    def __init__(self, value):
        self.value = value

    def __and__(self, obj):
        print("And operator overloaded")
        if isinstance(obj, Geek):
            return self.value & obj.value
        else:
            raise ValueError("Must be a object of class Geek")

    def __or__(self, obj):
        print("Or operator overloaded")
        if isinstance(obj, Geek):
            return self.value | obj.value
        else:
            raise ValueError("Must be a object of class Geek")

    def __xor__(self, obj):
        print("Xor operator overloaded")
        if isinstance(obj, Geek):
            return self.value ^ obj.value
        else:
            raise ValueError("Must be a object of class Geek")

    def __lshift__(self, obj):
        print("lshift operator overloaded")
        if isinstance(obj, Geek):
            return self.value << obj.value
        else:
            raise ValueError("Must be a object of class Geek")

    def __rshift__(self, obj):
        print("rshift operator overloaded")
        if isinstance(obj, Geek):
            return self.value >> obj.value
        else:
            raise ValueError("Must be a object of class Geek")

    def __invert__(self):
        print("Invert operator overloaded")
        return ~self.value


# Driver's code
if __name__ == "__main__":
    a = Geek(10)
    b = Geek(12)
    print(a & b)
    print(a | b)
    print(a ^ b)
    print(a << b)
    print(a >> b)
    print(~a)

Output: 

And operator overloaded
8
Or operator overloaded
14
Xor operator overloaded
8
lshift operator overloaded
40960
rshift operator overloaded
8
Invert operator overloaded
-11

Note: To know more about operator overloading click here.



Previous Article
Next Article

Similar Reads

G-Fact 19 (Logical and Bitwise Not Operators on Boolean)
Most of the languages including C, C++, Java, and Python provide a boolean type that can be either set to False or True. In this article, we will see about logical and bitwise not operators on boolean. Logical Not (or !) Operator in PythonIn Python, the logical not operator is used to invert the truth value of a Boolean expression, returning True i
4 min read
Division Operators in Python
Division Operators allow you to divide two numbers and return a quotient, i.e., the first number or number at the left is divided by the second number or number at the right and returns the quotient. Division Operators in PythonThere are two types of division operators: Float divisionInteger division( Floor division)When an integer is divided, the
5 min read
Python | Operators | Question 1
What is the output of the following code : C/C++ Code print 9//2 (A) 4.5 (B) 4.0 (C) 4 (D) Error Answer: (C)Explanation: The ‘//’ operator in Python returns the integer part of the floating number. Quiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 2
Which function overloads the &gt;&gt; operator? (A) more() (B) gt() (C) ge() (D) None of the above Answer: (D) Explanation: rshift() overloads the &gt;&gt; operatorQuiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 3
Which operator is overloaded by the or() function? (A) || (B) | (C) // (D) / Answer: (B) Explanation: or() function overloads the bitwise OR operatorQuiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Operators | Question 4
What is the output of the following program : C/C++ Code i = 0 while i (A) 0 2 1 3 2 4 (B) 0 1 2 3 4 5 (C) Error (D) 1 0 2 4 3 5 Answer: (C)Explanation: There is no operator ++ in Python Quiz of this QuestionPlease comment below if you find anything wrong in the above post
1 min read
Python | Solve given list containing numbers and arithmetic operators
Given a list containing numbers and arithmetic operators, the task is to solve the list. Example: Input: lst = [2, '+', 22, '+', 55, '+', 4] Output: 83 Input: lst = [12, '+', 8, '-', 5] Output: 15 Below are some ways to achieve the above tasks. Method #1: Using Iteration We can use iteration as the simplest approach to solve the list with importing
3 min read
Python | Splitting operators in String
Sometimes we have a source string to have certain mathematical statement for computations and we need to split both the numbers and operators as a list of individual elements. Let's discuss certain ways in which this problem can be performed. Method #1 : Using re.split() This task can be solved using the split functionality provided by Python regex
7 min read
Merging and Updating Dictionary Operators in Python 3.9
Python 3.9 is still in development and scheduled to be released in October this year. On Feb 26, alpha 4 versions have been released by the development team. One of the latest features in Python 3.9 is the merge and update operators. There are various ways in which Dictionaries can be merged by the use of various functions and constructors in Pytho
3 min read
Python 3 - Logical Operators
Logical Operators are used to perform certain logical operations on values and variables. These are the special reserved keywords that carry out some logical computations. The value the operator operates on is known as Operand. In Python, they are used on conditional statements (either True or False), and as a result, they return boolean only (True
4 min read
Article Tags :
Practice Tags :