Python Bitwise Operators - GeeksforGeeks (2024)

Last Updated : 21 May, 2024

Summarize

Comments

Improve

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 Bitwise Operators - GeeksforGeeks (1)

Python
a = 10b = 4# Print bitwise AND operationprint("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 Bitwise Operators - GeeksforGeeks (2)

Python
a = 10b = 4# Print bitwise OR operationprint("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 Bitwise Operators - GeeksforGeeks (3)

Python
a = 10b = 4# print bitwise XOR operationprint("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 Bitwise Operators - GeeksforGeeks (4)

Python
a = 10b = 4# Print bitwise NOT operationprint("~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 = 5Example 2:a = -10 = 1111 0110 (Binary)a >> 1 = 1111 1011 = -5 
Python
a = 10b = -10# print bitwise right shift operatorprint("a >> 1 =", a >> 1)print("b >> 1 =", b >> 1)

Output

a >> 1 = 5b >> 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 = 10a << 2 = 0001 0100 = 20 Example 2:b = -10 = 1111 0110 (Binary)b << 1 = 1110 1100 = -20b << 2 = 1101 1000 = -40 
Python
a = 5b = -10# print bitwise left shift operatorprint("a << 1 =", a << 1)print("b << 1 =", b << 1)

Output:

a << 1 = 10b << 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 overloadingclass 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 codeif __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 overloaded8Or operator overloaded14Xor operator overloaded8lshift operator overloaded40960rshift operator overloaded8Invert operator overloaded-11

Note: To know more about operator overloading click here.



N

nikhilaggarwal3

Python Bitwise Operators - GeeksforGeeks (5)

Improve

Previous Article

Ternary Operator in Python

Next Article

Assignment Operators in Python

Please Login to comment...

Python Bitwise Operators - GeeksforGeeks (2024)
Top Articles
BBC Business | Economy, Tech, AI, Work, Personal Finance, Market news
League of Legends Wild Rift Mobile Play store Download link, size and more
Katie Pavlich Bikini Photos
Gamevault Agent
Hocus Pocus Showtimes Near Harkins Theatres Yuma Palms 14
Free Atm For Emerald Card Near Me
Craigslist Mexico Cancun
Hendersonville (Tennessee) – Travel guide at Wikivoyage
Doby's Funeral Home Obituaries
Vardis Olive Garden (Georgioupolis, Kreta) ✈️ inkl. Flug buchen
Select Truck Greensboro
How To Cut Eelgrass Grounded
Pac Man Deviantart
Alexander Funeral Home Gallatin Obituaries
Craigslist In Flagstaff
Shasta County Most Wanted 2022
Energy Healing Conference Utah
Testberichte zu E-Bikes & Fahrrädern von PROPHETE.
Aaa Saugus Ma Appointment
Geometry Review Quiz 5 Answer Key
Walgreens Alma School And Dynamite
Bible Gateway passage: Revelation 3 - New Living Translation
Yisd Home Access Center
Home
Shadbase Get Out Of Jail
Gina Wilson Angle Addition Postulate
Celina Powell Lil Meech Video: A Controversial Encounter Shakes Social Media - Video Reddit Trend
Walmart Pharmacy Near Me Open
Dmv In Anoka
A Christmas Horse - Alison Senxation
Ou Football Brainiacs
Access a Shared Resource | Computing for Arts + Sciences
Pixel Combat Unblocked
Umn Biology
Cvs Sport Physicals
Mercedes W204 Belt Diagram
Rogold Extension
'Conan Exiles' 3.0 Guide: How To Unlock Spells And Sorcery
Teenbeautyfitness
Weekly Math Review Q4 3
Facebook Marketplace Marrero La
Nobodyhome.tv Reddit
Topos De Bolos Engraçados
Gregory (Five Nights at Freddy's)
Grand Valley State University Library Hours
Holzer Athena Portal
Hampton In And Suites Near Me
Stoughton Commuter Rail Schedule
Bedbathandbeyond Flemington Nj
Free Carnival-themed Google Slides & PowerPoint templates
Otter Bustr
Selly Medaline
Latest Posts
Article information

Author: Chrissy Homenick

Last Updated:

Views: 5793

Rating: 4.3 / 5 (54 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Chrissy Homenick

Birthday: 2001-10-22

Address: 611 Kuhn Oval, Feltonbury, NY 02783-3818

Phone: +96619177651654

Job: Mining Representative

Hobby: amateur radio, Sculling, Knife making, Gardening, Watching movies, Gunsmithing, Video gaming

Introduction: My name is Chrissy Homenick, I am a tender, funny, determined, tender, glorious, fancy, enthusiastic person who loves writing and wants to share my knowledge and understanding with you.