×

Python Bitwise Operators

When used with variables and objects in an expression, operators are tokens that carry out calculations. The variables and items to which the computation is applied are known as operands. As a result, an operator needs some operands to work with.

The operators and their function are briefly described in the following lists. However, we shall concentrate on Bitwise Operators in this article.

  • Unary Operators

    Unary operators are those that only have one operand to work with. Unary Operators are listed below:
    • +     Unary Plus
    • -      Unary Minus
    • ~     Bitwise Compliment  
    • not  Logical Negation
  • Binary Operators
    Binary operators are those that operate on two operands. Some binary operators are as follows:
    • Arithmetic Operators
      • Subtraction
      • +  Addition
      • *   ­­ Multiplication
      • /     Division
      • //    Floor Division
      • %   Modulus/ Remainder
      • **  Raise to the power/ Exponent
    • Bitwise Operators
      • & Bitwise AND
      • ^   Bitwise Exclusive OR (i.e., XOR)
      • |    Bitwise OR
    • Shift Operators
      • << Shift Left
      • >> Shift Right
    • Identity Operators
      • is -> is the identity same?
      • is not -> is the identity not same?
    • Relational Operators
      • < Less than
      • < Greater than
      • <=  Less than or Equal to
      • >=  Greater than or Equal to
      • ==  Equal to
      • != Not equal to
    • Assignment Operators
      • =  Assignment
      • /=    Assign Quotient
      • +=   Assign Sum
      • *=   Assign Product
      • %=  Assign Remainder
      • -=    Assign Difference
      • **=  Assign Exponent
      • //=    Assign Floor Division
    • Logical Operators
      • and  Logical AND
      • or    Logical OR
    • Membership Operators
      • in   whether variable is in the sequence
      • not in   whether variable not in sequence

        Now let’s dig in detail about Python Bitwise Operators.
  • Python Bitwise Operators
    In Python, bitwise operations are carried out on integers using bitwise operators. In order to carry out Bitwise operations In Python on integers, bitwise operators can be used. The Bitwise Operator is called so because its operations are carried out bit by bit once the integers are converted to binary. The outcome is then shown in decimal form.

    One thing to pin-point is that, only integers are supported by Python's bitwise operators.

    The Bitwise Operators and their Functions are Briefly Described in the Following List:
    • & Bitwise AND
    • |      Bitwise OR
    • ^     Bitwise XOR
    • ~     Bitwise NOT
    • >> Bitwise Right Shift
    • << Bitwise Left Shift

Syntax:

& -> a & b
| ->  a | b
^ ->  a ^ b
~ ->  ~ a
>> -> a>>
<< -> <<b

Here, a and b are integers.

  • Bitwise AND Operator( &)
    It returns 1 in the case where the bits present are both 1; otherwise, returns 0.

For Example:

x = 4 (In Binary ->  0100)
y = 10 (In Binary -> 1010)


x & y = 0100 & 1010
= 0000 = 0 (decimal)
  • Bitwise OR Operator ( | )
    Returns 1 if either bit is 1, otherwise 0.

    For Example:
x = 4 (In Binary -> 0100
y = 10 (In Binary -> 1010)
x | y =  0100 | 1010 
= 1110 = 14 (decimal)
  • Bitwise Not Operator ( ~ )
    One's complement is returned of the number.

For Example:

x = 4 (In Binary -> 0100)
~ x = ~ 4 = ~ 0100
= - (0100 + 1)
= - 5 (decimal)
  • Bitwise XOR Operator ( ^ )
    If one of the bits is 1 and the other is 0, returns true; otherwise, returns false.

For Example:

x = 4 (In Binary  0100)

y = 10 (In Binary  1010)

x ^ y = 4 ^ 10 = 0100 ^ 1010

= 1110 = 14 (decimal)

Code:

x = 10
y = 4
print("x & y =", x & y) # bitwise AND operation 
print("x | y =", x | y) # bitwise OR operation
print("~x =", ~x) # bitwise NOT operation
print("x ^ y =", x ^ y) # print bitwise XOR operation

Output:

Python Bitwise Operators

Shift Operator

These operators shift the bits of a number to the left or right, multiplying or dividing it by two, accordingly. In the program,sometimes we need to multiply or divide a number by it and this is the case where we can use Shift Operators.

1.Bitwise left shift
Shifts the number's bits to the left, filling vacancies on the right with 0 as a result. Multiplying a number by a power of two has a similar effect.
For Example1:

x = 5 = 0000 0101 (In Binary)

x << 1 = 0000 1010 = 10

x << 2 = 0001 0100 = 20

For Example 2:

y = -10 = 1111 0110 (  In Binary)

y<< 1 = 1110 1100 = -20

y << 2 = 1101 1000 = -40

2. Bitwise right shift

Shifts the bits of the number to the right, filling the vacancies on the left with 0 (or 1 if the value is negative). The result is similar to dividing a number by a power of two.

For Example 1:

x = 10 = 0000 1010 (  In Binary)

x >> 1 = 0000 0101 = 5

For Example 2:

x = -10 = 1111 0110 (  In Binary)

x >> 1 = 1111 1011 = -5

Code:

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


a = 15
b = -8
print("a << 1 =", a << 1)#bitwise left shift operator --> print
print("b << 1 =", b << 1)#bitwise left shift operator --> print

Output:

Python Bitwise Operators

Overloading of the Bitwise Operator

Overloading an operator refers to giving them more meaning than their established operational meaning. For instance, the + operator can be used to combine two lists, join two strings, and add two integers.

It is feasible due to the fact that the int and str classes override the '+' operator. When the same built-in operator or method operates differently for objects of different classes, this is referred to as operator overloading.

A basic example of Bitwise operator overloading is shown below:

Code:

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


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


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


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


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


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


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




if __name__ == "__main__":
    a = OperOver(12)
    b = OperOver(32)
print(a & b)
print(a | b)
print(a ^ b)
print(a << b)
print(a >> b)
    print(~a)

Output:

Python Bitwise Operators

Related Topics

Python Support

Python Python is an interactive and more accessible language than any other programming language. The python programming language uses a variety of libraries to perform the operations in a faster way....

3 minutes read.

How to create a DataFrames in Python

How to create a DataFrames in Python Data Frame is a data structure in which data is stored in tabular form. They can also be referred as two-dimensional collection of data. Various...

5 minutes read.

Python Program to Print all the Prime Number in an Interval

Python Program to Print all the Prime Number in an Interval What is Prime numbers? A prime number is referred to those numbers that can be divisible by them only. In simple words,...

4 minutes read.

Python Pass Statement

The pass statement is a null statement. The difference between pass and comment is that comment is ignored by the interpreter, whereas pass is not. The pass statement is typically used...

3 minutes read.

Best Python AI Projects

Artificial consciousness is advancing quickly, from Chabot's to self-driving vehicles. Because of the various advantages and development presented by AI, numerous enterprises have begun searching for AI-fueled applications. Thus, there...

7 minutes read.

NSE Tools In Python

About NSE NSE (National Stock Exchange) of India Limited is the advanced stock exchange of India. It is located in Mumbai, Maharastra and It was organized in 1992. It was...

2 minutes read.

Python List Methods

Python List Methods Python has a set of built-in methods that you can use on lists or arrays. Following are all of the methods of list objects: Methods Explanation append The list.append() method...

3 minutes read.

Sublime Python

SUBLIME: A compact, cross-platform code editor called Sublime Text 3 (ST3) is well-known for its quickness, usability, and robust community support. Although it's a fantastic editor out of the box, its...

6 minutes read.

Create the First GUI Application using PyQt5 in Python

GUI: A graphical user interface, or GUI, is present on most personal computers. It provides a simple experience for individuals with various computing skill levels. GUI apps may take more resources...

3 minutes read.

Pointers in Python

In this tutorial, we will study what pointers are and if they have any utility in python. Now, let us understand what pointers are Pointers Pointers are special variables used to store the...

3 minutes read.

Operator Overloading in Python

In any programming language, + is an arithmetic operator; it adds two numbers to give the sum. Have you ever tried to concatenate two strings? Concatenating two strings is adding...

5 minutes read.

Front end in python

Python : Python is an object oriented programming language which is highly interpreted and is highly interactive. Python was created by Guido van Rossum in the year 1985 – 1990 .The...

4 minutes read.

Python while loop

Loops are essential in Python or any other programming language, as they help to execute a block of code repetitively. Sometimes, situations arise where you would need to use a piece of code...

2 minutes read.

Python Dictionary popitem() method

Python Dictionary popitem() method The dictionary.popitem() method in Python removes the item that was last inserted into the dictionary. Syntax dictionary.popitem() Parameter NA Return This method returns an arbitrary element (key, value) pair from the given dictionary...

1 minute read.

Python Escape Characters

In this tutorial, we will learn how to use the Escape Characters in Python. Escape Character: Escape Characters are used for some special meaning in our statements. It is denoted or represented...

3 minutes read.

Python Program to Print Sum of all Elements in an Array

Python program to print sum of all elements in an array A set of objects stored in contiguous memory locations is referred to as an array. The concept is to keep...

2 minutes read.

Python Empty Tuple

How to Create an Empty Tuple Tuple A tuple is a data structure used to store non-homogeneous data elements. These non-homogeneous data elements consist of integer data type, character data type, String...

3 minutes read.

Python Slice from Last Occurrence of K

Introduction We already know that in Python, cutting produces a sub-string out of a string. The variables start, stop, and step are used to set the slicing range. When dealing on...

3 minutes read.

Python datetime

Python provides a module named datetime to work with the date and time. Sometimes in the real life application development, we need to work with the date and time. The date is...

3 minutes read.

Python Not Equal Operator

Python provides us with many operators to make tasks easier. There are about 7 categories of operators in Python. One of the 7 classifications is the comparison operators. Just as...

3 minutes read.