The Wayback Machine - https://web.archive.org/web/20241013185711/https://www.geeksforgeeks.org/python-bitwise-operators/
Open In App

Python Bitwise Operators

Last Updated : 21 May, 2024
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

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.

Image

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

Image

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

Image

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.

Image

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
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 >> operator? (A) more() (B) gt() (C) ge() (D) None of the above Answer: (D) Explanation: rshift() overloads the >> 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
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
How To Do Math in Python 3 with Operators?
Python3 provides us data types like integer and float along with various operators to perform mathematical calculations for graph plotting, machine learning algorithms, Statistical, data analytical purposes. An operator is a symbol that performs specific operations, which is very useful if one is frequently dealing with numbers. Operator precedence
5 min read
Precedence and Associativity of Operators in Python
In Python, operators have different levels of precedence, which determine the order in which they are evaluated. When multiple operators are present in an expression, the ones with higher precedence are evaluated first. In the case of operators with the same precedence, their associativity comes into play, determining the order of evaluation. Opera
4 min read
Augmented Assignment Operators in Python
An assignment operator is an operator that is used to assign some value to a variable. Like normally in Python, we write "a = 5" to assign value 5 to variable 'a'. Augmented assignment operators have a special role to play in Python programming. It basically combines the functioning of the arithmetic or bitwise operator with the assignment operator
4 min read
Inplace Operators in Python | Set 1 (iadd(), isub(), iconcat()...)
Python in its definition provides methods to perform inplace operations, i.e. doing assignments and computations in a single statement using an operator module. Example x += y is equivalent to x = operator.iadd(x, y) Inplace Operators in PythonBelow are some of the important Inplace operators in Python: iadd()isub()iconcat()imul()itruediv()imod()ia
3 min read
Inplace Operators in Python | Set 2 (ixor(), iand(), ipow(),…)
Inplace Operators in Python | Set 1(iadd(), isub(), iconcat()…) More functions are discussed in this articles. 1. ixor() :- This function is used to assign and xor the current value. This operation does "a^ = b" operation. Assigning is not performed in case of immutable containers, such as strings, numbers and tuples. 2. ipow() :- This function is
3 min read
Inplace vs Standard Operators in Python
Inplace Operators - Set 1, Set 2Normal operators do the simple assigning job. On other hand, Inplace operators behave similarly to normal operators except that they act in a different manner in case of mutable and Immutable targets. The _add_ method, does simple addition, takes two arguments, returns the sum, and stores it in another variable witho
3 min read
Chaining comparison operators in Python
Checking more than two conditions is very common in Programming Languages. Let's say we want to check the below condition: a < b < c The most common syntax to do it is as follows: if a < b and b < c : {...} In Python, there is a better way to write this using the Comparison operator Chaining. The chaining of operators can be written as
5 min read
Increment += and Decrement -= Assignment Operators in Python
If you're familiar with Python, you would have known Increment and Decrement operators ( both pre and post) are not allowed in it. Python is designed to be consistent and readable. One common error by a novice programmer in languages with ++ and -- operators are mixing up the differences (both in precedence and in return value) between pre and post
3 min read
Python Operators
In Python programming, Operators in general are used to perform operations on values and variables. These are standard symbols used for logical and arithmetic operations. In this article, we will look into different types of Python operators.  OPERATORS: These are the special symbols. Eg- + , * , /, etc.OPERAND: It is the value on which the operato
12 min read
Comparison Operators in Python
The Python operators can be used with various data types, including numbers, strings, booleans, and more. In Python, comparison operators are used to compare the values of two operands (elements being compared). When comparing strings, the comparison is based on the alphabetical order of their characters (lexicographic order).Be cautious when compa
5 min read
Python Membership and Identity Operators
There is a large set of Python operators that can be used on different datatypes. Sometimes we need to know if a value belongs to a particular set. This can be done by using the Membership and Identity Operators. In this article, we will learn about Python Membership and Identity Operators. Table of Content Python Membership OperatorsPython IN Oper
7 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
6 min read
Python Logical Operators
Python logical operators are used to combine conditional statements, allowing you to perform operations based on multiple conditions. These Python operators, alongside arithmetic operators, are special symbols used to carry out computations on values and variables. In this article, we will discuss logical operators in Python definition and also loo
6 min read
Python Arithmetic Operators
The Python operators are fundamental for performing mathematical calculations in programming languages like Python, Java, C++, and many others. Arithmetic operators are symbols used to perform mathematical operations on numerical values. In most programming languages, arithmetic operators include addition (+), subtraction (-), multiplication (*), d
5 min read
Assignment Operators in Python
The Python Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic, logical, and bitwise computations. The value the operator operates on is known as the Operand. Here, we will cover Different Assignment operators in Python. Operators Sign Description SyntaxAssignment Operator = Assi
11 min read
Why Are There No ++ and -- Operators in Python?
Python does not include the ++ and -- operators that are common in languages like C, C++, and Java. This design choice aligns with Python's focus on simplicity, clarity, and reducing potential confusion. In this article, we will see why Python does not include these operators and how you can achieve similar functionality using Pythonic alternatives
3 min read
Tensorflow bitwise.bitwise_xor() method - Python
Tensorflow bitwise.bitwise_xor() method performs the bitwise_xor operation and the result will set those bits, that are different in a and b. The operation is done on the representation of a and b. This method belongs to bitwise module. Syntax: tf.bitwise.bitwise_xor(a, b, name=None) Arguments a: This must be a Tensor.It should be from the one of t
2 min read
Python - Tensorflow bitwise.left_shift() method
Tensorflow bitwise.left_shift() method performs the left_shift operation on input a defined by input b and return the new constant. The operation is done on the representation of a and b. This method belongs to bitwise module. Syntax: tf.bitwise.left_shift( a, b, name=None) Arguments a: This must be a Tensor.It should be from the one of the followi
2 min read
Python - Tensorflow bitwise.bitwise_and() method
Tensorflow bitwise.bitwise_and() method performs the bitwise_and operation and return those bits set, that are set(1) in both a and b. The operation is done on the representation of a and b. This method belongs to bitwise module. Syntax: tf.bitwise.bitwise_and( a, b, name=None) Arguments a: This must be a Tensor.It should be from the one of the fol
2 min read
Python - Tensorflow bitwise.invert() method
Tensorflow bitwise.invert() method performs the invert operation and the result will invert the bits, Like 0 to 1 and 1 to 0. The operation is done on the representation of a. This method belongs to bitwise module. Syntax: tf.bitwise.invert( a, name=None) Arguments a: This must be a Tensor.It should be from the one of the following types: int8, int
2 min read
Python - Tensorflow bitwise.bitwise_or() method
Tensorflow bitwise.bitwise_or() method performs the bitwise_or operation and return those bits set, that are either set(1) in a or in b or in both. The operation is done on the representation of a and b. This method belongs to bitwise module. Syntax: tf.bitwise.bitwise_or( a, b, name=None) Arguments a: This must be a Tensor.It should be from the on
2 min read
Python - Tensorflow bitwise.right_shift() method
Tensorflow bitwise.right_shift() method performs the right_shift operation on input a defined by input b and return the new constant. The operation is done on the representation of a and b. This method belongs to bitwise module. Syntax: tf.bitwise.right_shift( a, b, name=None) Arguments a: This must be a Tensor. It should be from the one of the fol
2 min read
Operators Precedence in Scala
An operator is a symbol that represents an operation to be performed with one or more operand. Operators are the foundation of any programming language. Which operator is performed first in an expression with more than one operators with different precedence is determined by operator precedence. For example, 10 + 20 * 30 is calculated as 10 + (20 *
3 min read
Article Tags :
Practice Tags :