Tutorial Playlist
200 Lessons1. Introduction to Python
2. Features of Python
3. How to install python in windows
4. How to Install Python on macOS
5. Install Python on Linux
6. Hello World Program in Python
7. Python Variables
8. Global Variable in Python
9. Python Keywords and Identifiers
10. Assert Keyword in Python
11. Comments in Python
12. Escape Sequence in Python
13. Print In Python
14. Python-if-else-statement
15. Python for Loop
16. Nested for loop in Python
17. While Loop in Python
18. Python’s do-while Loop
19. Break in Python
20. Break Pass and Continue Statement in Python
21. Python Try Except
22. Data Types in Python
23. Float in Python
24. String Methods Python
25. List in Python
26. List Methods in Python
27. Tuples in Python
28. Dictionary in Python
29. Set in Python
30. Operators in Python
31. Boolean Operators in Python
32. Arithmetic Operators in Python
33. Assignment Operator in Python
34. Bitwise operators in Python
Now Reading
35. Identity Operator in Python
36. Operator Precedence in Python
37. Functions in Python
38. Lambda and Anonymous Function in Python
39. Range Function in Python
40. len() Function in Python
41. How to Use Lambda Functions in Python?
42. Random Function in Python
43. Python __init__() Function
44. String Split function in Python
45. Round function in Python
46. Find Function in Python
47. How to Call a Function in Python?
48. Python Functions Scope
49. Method Overloading in Python
50. Method Overriding in Python
51. Static Method in Python
52. Python List Index Method
53. Python Modules
54. Math Module in Python
55. Module and Package in Python
56. OS module in Python
57. Python Packages
58. OOPs Concepts in Python
59. Class in Python
60. Abstract Class in Python
61. Object in Python
62. Constructor in Python
63. Inheritance in Python
64. Multiple Inheritance in Python
65. Encapsulation in Python
66. Data Abstraction in Python
67. Opening and closing files in Python
68. How to open JSON file in Python
69. Read CSV Files in Python
70. How to Read a File in Python
71. How to Open a File in Python?
72. Python Write to File
73. JSON Python
74. Python JSON – How to Convert a String to JSON
75. Python JSON Encoding and Decoding
76. Exception Handling in Python
77. Recursion in Python
78. Python Decorators
79. Python Threading
80. Multithreading in Python
81. Multiprocеssing in Python
82. Python Regular Expressions
83. Enumerate() in Python
84. Map in Python
85. Filter in Python
86. Eval in Python
87. Difference Between List, Tuple, Set, and Dictionary in Python
88. List to String in Python
89. Linked List in Python
90. Length of list in Python
91. Reverse a List in Python
92. Python List remove() Method
93. How to Add Elements in a List in Python
94. How to Reverse a List in Python?
95. Difference Between List and Tuple in Python
96. List Slicing in Python
97. Sort in Python
98. Merge Sort in Python
99. Selection Sort in Python
100. Sort Array in Python
101. Sort Dictionary by Value in Python
102. Datetime Python
103. Random Number in Python
104. 2D Array in Python
105. Abs in Python
106. Advantages of Python
107. Anagram Program in Python
108. Append in Python
109. Applications of Python
110. Armstrong Number in Python
111. Assert in Python
112. Binary Search in Python
113. Binary to Decimal in Python
114. Bool in Python
115. Calculator Program in Python
116. chr in Python
117. Control Flow Statements in Python
118. Convert String to Datetime Python
119. Count in python
120. Counter in Python
121. Data Visualization in Python
122. Datetime in Python
123. Extend in Python
124. F-string in Python
125. Fibonacci Series in Python
126. Format in Python
127. GCD of Two Numbers in Python
128. How to Become a Python Developer
129. How to Run Python Program
130. In Which Year Was the Python Language Developed?
131. Indentation in Python
132. Index in Python
133. Interface in Python
134. Is Python Case Sensitive?
135. Isalpha in Python
136. Isinstance() in Python
137. Iterator in Python
138. Join in Python
139. Leap Year Program in Python
140. Lexicographical Order in Python
141. Literals in Python
142. Matplotlib
143. Matrix Multiplication in Python
144. Memory Management in Python
145. Modulus in Python
146. Mutable and Immutable in Python
147. Namespace and Scope in Python
148. OpenCV Python
149. Operator Overloading in Python
150. ord in Python
151. Palindrome in Python
152. Pass in Python
153. Pattern Program in Python
154. Perfect Number in Python
155. Permutation and Combination in Python
156. Prime Number Program in Python
157. Python Arrays
158. Python Automation Projects Ideas
159. Python Frameworks
160. Python Graphical User Interface GUI
161. Python IDE
162. Python input and output
163. Python Installation on Windows
164. Python Object-Oriented Programming
165. Python PIP
166. Python Seaborn
167. Python Slicing
168. type() function in Python
169. Queue in Python
170. Replace in Python
171. Reverse a Number in Python
172. Reverse a string in Python
173. Reverse String in Python
174. Stack in Python
175. scikit-learn
176. Selenium with Python
177. Self in Python
178. Sleep in Python
179. Speech Recognition in Python
180. Split in Python
181. Square Root in Python
182. String Comparison in Python
183. String Formatting in Python
184. String Slicing in Python
185. Strip in Python
186. Subprocess in Python
187. Substring in Python
188. Sum of Digits of a Number in Python
189. Sum of n Natural Numbers in Python
190. Sum of Prime Numbers in Python
191. Switch Case in Python
192. Python Program to Transpose a Matrix
193. Type Casting in Python
194. What are Lists in Python?
195. Ways to Define a Block of Code
196. What is Pygame
197. Why Python is Interpreted Language?
198. XOR in Python
199. Yield in Python
200. Zip in Python
Bitwise operators in Python are fundamental tools for performing bit-level operations on integers. These operators manipulate individual bits, allowing for efficient and precise control over binary data. In this extensive guide, we'll delve into the details of bitwise operator in Python, exploring their purpose, functionality, and practical applications.
Bitwise operators are essential in low-level programming, embedded systems, and tasks that require fine-grained bit manipulation. Python provides several bitwise operators, each serving a unique purpose. These operators include AND, OR, NOT, XOR, and shift operators. Let's explore each of these in detail.
Bitwise operators in Python are fundamental operations that work at the binary level, enabling precise control over binary data. They perform operations on individual bits of integers by converting the integers to binary format, performing bit-level operations, and then converting the result back to decimal form. These operators are used for tasks such as bit manipulation, flag settings, and low-level data processing.
Operator | Description | Example | Result (Decimal) |
Bitwise AND (&) | Returns 1 if both bits are 1, else 0 | 5 & 3 | 1 |
Bitwise OR (` | `) | Returns 1 if at least one bit is 1, else 0 | `5 |
Bitwise NOT (~) | Inverts all bits | ~5 | -6 |
Bitwise XOR (^) | Returns 1 if bits are different else, 0 | 5 ^ 3 | 6 |
The bitwise AND operator (&) is used to perform a binary AND operation on corresponding bits of two integers. It returns a new integer with bits set to 1 only if both operands have corresponding bits set to 1.
Example:
Code
a = 5 # 101 in binary
b = 3 # 011 in binary
result = a & b # 001 in binary, which is 1 in decimal
The bitwise OR operator (|) is used to perform a binary OR operation on corresponding bits of two integers. It returns a new integer with bits set to 1 if at least one of the corresponding bits in the operands is 1.
Example:
Code
a = 5 # 101 in binary
b = 3 # 011 in binary
result = a | b # 111 in binary, which is 7 in decimal
The bitwise NOT operator in Python (~) inverts all the bits of a single integer. It returns a new integer with all bits reversed (0s become 1s, and 1s become 0s).
Example:
Code
a = 5 # 101 in binary
result = ~a # -6 in decimal
The bitwise XOR operator in Python (^) is used to perform a binary XOR operation on corresponding bits of two integers. It returns a new integer with bits set to 1 if exactly one of the corresponding bits in the operands is 1.
Example:
Code
a = 5 # 101 in binary
b = 3 # 011 in binary
result = a ^ b # 110 in binary, which is 6 in decimal
Here is Python code that demonstrates the bitwise logical operators in Python (&, |, ~, ^) in action:
Code
# Bitwise AND operator (&)
a = 12 # Binary: 1100
b = 6 # Binary: 0110
result_and = a & b # Binary result: 0100 (Decimal: 4)
# Bitwise OR operator (|)
x = 10 # Binary: 1010
y = 3 # Binary: 0011
result_or = x | y # Binary result: 1011 (Decimal: 11)
# Bitwise NOT operator in Python (~)
m = 7 # Binary: 0111
result_not = ~m # Binary result: 1000 (Decimal: -8)
# Bitwise XOR operator in Python(^)
p = 15 # Binary: 1111
q = 6 # Binary: 0110
result_xor = p ^ q # Binary result: 1001 (Decimal: 9)
# Printing the results
print("Bitwise AND result:", result_and)
print("Bitwise OR result:", result_or)
print("Bitwise NOT result:", result_not)
print("Bitwise XOR result:", result_xor)
In this code:
Output:
Bitwise AND result: 4
Bitwise OR result: 11
Bitwise NOT result: -8
Bitwise XOR result: 9
Bitwise Shift Operators are operators in Python used to shift the bits of an integer left or right by a specified number of positions. These bitwise left and right shift operators in Python manipulate the binary representation of an integer, multiplying or dividing it by powers of 2.
Bitwise left and right shift operator in Python | Description | Example | Result (Decimal) |
Bitwise Left Shift (<<) | Shifts bits left by specified count | 5 << 2 | 20 |
Bitwise Right Shift (>>) | Shifts bits right by specified count | 16 >> 2 | 4 |
The bitwise right shift operator in Python (>>) shifts the bits of an integer to the right by a specified number of positions. This operation effectively divides the integer by 2, raised to the power of the specified number.
Example:
Code
a = 8 # 1000 in binary
result = a >> 2 # Shift right by 2 positions: 0010 in binary, which is 2 in decimal
The bitwise left shift operator in Python (<<) shifts the bits of an integer to the left by a specified number of positions. This operation effectively multiplies the integer by 2 raised to the power of the specified number.
Example:
Code
a = 2 # 0010 in binary
result = a << 3 # Shift left by 3 positions: 1000 in binary, which is 8 in decimal
Here's Python code that demonstrates the bitwise shift operators (<< and >>) in action:
Code
# Bitwise Left Shift operator in Python (<<)
num_left = 5 # Binary: 0000 0101
shift_count = 2
result_left_shift = num_left << shift_count # Shift left by 2 positions: 0001 0100 (Decimal: 20)
# Bitwise Right Shift operator in Python (>>)
num_right = 16 # Binary: 0001 0000
shift_count = 2
result_right_shift = num_right >> shift_count # Shift right by 2 positions: 0000 0100 (Decimal: 4)
# Printing the results
print("Bitwise Left Shift result:", result_left_shift)
print("Bitwise Right Shift result:", result_right_shift)
In this code:
Output:
Bitwise Left Shift result: 20
Bitwise Right Shift result: 4
Python allows you to overload some bitwise operators (&, |, ~, ^) for custom classes by defining special methods such as __and__(), __or__(), __invert__(), and __xor__().
Overloading these operators lets you define custom behavior for bitwise operations when working with your objects.
Code
class ComplexNumber:
def __init__(self, real, imaginary):
self.real = real
self.imaginary = imaginary
def __str__(self):
return f"{self.real} {self.imaginary}i"
def __add__(self, other):
if isinstance(other, ComplexNumber):
real_sum = self.real other.real
imag_sum = self.imaginary other.imaginary
return ComplexNumber(real_sum, imag_sum)
else:
raise ValueError("Addition is only supported for ComplexNumber objects.")
# Usage
num1 = ComplexNumber(2, 3)
num2 = ComplexNumber(1, 4)
result = num1+num2
print(result) # Output: 3+7i
Code
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def __str__(self):
return f"Point({self.x}, {self.y})"
def __sub__(self, other):
if isinstance(other, Point):
x_diff = self.x - other.x
y_diff = self.y - other.y
return Point(x_diff, y_diff)
else:
raise ValueError("Subtraction is only supported for Point objects.")
# Usage
point1 = Point(5, 3)
point2 = Point(2, 2)
result = point1 - point2
print(result) # Output: Point(3, 1)
Code
class Matrix:
def __init__(self, data):
self.data = data
def __str__(self):
return "\n".join([" ".join(map(str, row)) for row in self.data])
def __mul__(self, other):
if isinstance(other, Matrix):
result = [[0 for _ in range(len(other.data[0]))] for _ in range(len(self.data))]
for i in range(len(self.data)):
for j in range(len(other.data[0])):
for k in range(len(other.data)):
result[i][j] = self.data[i][k] * other.data[k][j]
return Matrix(result)
else:
raise ValueError("Multiplication is only supported for Matrix objects.")
# Usage
matrix1 = Matrix([[1, 2], [3, 4]])
matrix2 = Matrix([[5, 6], [7, 8]])
result = matrix1 * matrix2
print(result)
# Output:
# 19 22
# 43 50
Code
class Fraction:
def __init__(self, numerator, denominator):
self.numerator = numerator
self.denominator = denominator
def __str__(self):
return f"{self.numerator}/{self.denominator}"
def __truediv__(self, other):
if isinstance(other, Fraction):
result_numerator = self.numerator * other.denominator
result_denominator = self.denominator * other.numerator
return Fraction(result_numerator, result_denominator)
else:
raise ValueError("Division is only supported for Fraction objects.")
# Usage
fraction1 = Fraction(1, 2)
fraction2 = Fraction(3, 4)
result = fraction1 / fraction2
print(result) # Output: 2/3
Now that we understand the bitwise operators and their functionality, let's explore some practical applications of these operators in Python.
1. Binary Data Manipulation:
Bitwise operators are invaluable when dealing with binary data, such as file I/O, image processing, or cryptography. For example, you can use bitwise AND to apply masks to specific bits in a binary stream or perform bitwise XOR operations for encryption.
2. Embedded Systems and Microcontrollers:
In embedded systems programming, where resource efficiency is crucial, bitwise operations are extensively used. Controlling hardware peripherals, setting configuration registers, and handling communication protocols often require precise bit manipulation.
3. Networking and IP Addressing:
In networking, IP address manipulation often involves bitwise operations. For instance, subnet masking and CIDR notation rely on bitwise AND to determine network and host portions of an IP address.
4. Graphics and Image Processing:
Bitwise operators are fundamental in graphics and image processing applications. They are used to manipulate pixel values, apply filters, and create various visual effects.
5. Game Development:
Game developers use bitwise operations for tasks such as collision detection, game state management, and rendering optimizations. These operations help enhance the performance and visual appeal of video games.
6. Ethical and Societal Implications:
While bitwise operators themselves are tools, the applications built on top of them can have profound ethical and societal implications. Here are some key considerations.
Bitwise operators in Python are powerful tools for working with binary data and performing bit-level operations on integers. It is essential for developers to understand their functionality and practical applications, especially those working in low-level programming, embedded systems, or data manipulation tasks.
1. What are bitwise operators?
Bitwise operators in Python are used to perform bit-level operations on integers. They include AND (&), OR (|), NOT (~), XOR (^), and shift operators (>> and <<).
2. Where are bitwise operators commonly used?
Bitwise operators are commonly used in low-level programming, embedded systems, binary data manipulation, networking, image processing, game development, and more.
3. How do I use bitwise operators in Python?
You can use bitwise operators by applying them to integers in binary representation. For example, to perform a bitwise AND operation between a and b, use the expression result = a & b.
PAVAN VADAPALLI
Director of Engineering
Director of Engineering @ upGrad. Motivated to leverage technology to solve problems. Seasoned leader for startups and fast moving orgs. Working …Read More
Popular
Talk to our experts. We’re available 24/7.
Indian Nationals
1800 210 2020
Foreign Nationals
+918045604032
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enrolling. upGrad does not make any representations regarding the recognition or equivalence of the credits or credentials awarded, unless otherwise expressly stated. Success depends on individual qualifications, experience, and efforts in seeking employment.
upGrad does not grant credit; credits are granted, accepted or transferred at the sole discretion of the relevant educational institution offering the diploma or degree. We advise you to enquire further regarding the suitability of this program for your academic, professional requirements and job prospects before enr...