×

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 String ljust() method

Python String ljust() method The string.ljust() method in Python will left align the string, where the padding is done using the parameter fillchar (space is default). Syntax String.ljust(width[, fillchar]) Parameter width: This parameter represents the...

2 minutes read.

Importing Numpy in Pycharm

Numpy : Numpy is one of the important library in python. The abbreviation of numpy is “Numerical python” or “Numeric Python”. This library is mainly used to access arrays. Numpy was created...

5 minutes read.

Python Validator

Validator  The validator is a library available in the python programming language. The library in python consists of all the related modules which can be imported to perform the required operation....

3 minutes read.

Difference between Input() and raw_input() functions in Python

There are two input functions in Python that are used for taking input are given below: raw_input()input() What is raw_input() Function? raw_input() function is a built-in function in Python. It is used to...

6 minutes read.

Captcha Code in Python with Example

Python Programming Language Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

6 minutes read.

_dict_ in Python

An unordered collection of data values known as a dictionary can be used in Python to store data values similar to a map. Dictionaries can also store a key: value...

6 minutes read.

Best Database for Python

Database The collection of structured data or information in an organized format in a computer system is known as Database. The data is inserted, deleted, updated, controlled, or manipulated in a...

6 minutes read.

What is Sleeping Time in Python

Did you ever postpone a Python program's execution? Usually, you want your code to execute as quickly as possible. But there are times when it is in your best interests...

3 minutes read.

Python Set discard() method

Python Set discard() method The set.discard() method in Python removes a specified element from the set (if present). Syntax set.discard(value) Parameter value- This parameter represents the element to be removed from the set. Return None Example 1 # Python program explaining # the...

1 minute read.

Scraping data in python

Data scraping is a technique in which one program extracts a set of data from the output of another program. Web scraping is the most common application of this technique....

6 minutes read.

Python program to print calendar

Python program to print the calendar This article will explain how to print the calendar of month and year using Python's calendar module. It's a straightforward thing in Python by importing...

1 minute read.

Latest Project Ideas using Python 2024

Python is one of the well-known languages for programming in the contemporary domain of computer science. The demand to adopt Python for IT purposes is steadily increasing because of its...

7 minutes read.

Python Subprocess Call Example

Python Programming Language: Python programming language is one of the most used programming languages, as it is used widely in the field of software and data analysis, web development, etc. It...

4 minutes read.

How to Print Pattern in Python

How to Print Pattern in Python. Pattern programs are really important for beginners and they are always asked in all the technical interviews. Multiple loops approach is used to print the different...

6 minutes read.

Python for loop

 Python for loop A for loop in Python executes a block of code for a specified number of times, based on a given sequence. The for loop in Python is different than any other...

3 minutes read.

Python str() function

Python str() function The str() function in Python converts the specified value into a string. Syntax class str(object='')           or class str(object=b'', encoding='utf-8', errors='strict') Parameter object:  This parameter represents any object to convert the given...

1 minute read.

Python If-else statement

In real life, there are situations where we have to make decisions for a particular circumstance and based on those decisions, and we plan our next move. The same thing...

4 minutes read.

Spyder (32-bit) - Free download

Spyder is a free and open-source scientific environment created by and for Python engineers, scientists, and data analysts. It is a robust scientific environment created in Python by and for...

3 minutes read.

Python Filter List

To filter a list, we use filter () method function. The filter () will test every element true or not in the sequence. Syntax: Filter(function, sequence) Parameters: Function: Function that check and verifies if...

2 minutes read.

Time. Sleep() in Python

Python time sleep () function suspends execution for a certain seconds given by user. Time sleep () syntax: Sleep(seconds) Limitations: The number of seconds to be suspends the code as per its requirements. Returns: Void The execution...

3 minutes read.