Using Bitwise Operators in Python
Course: Python Training Course
Topic: Using Bitwise Operators
Course Link: Python Training Course – JustAcademy
Demo Registration: Register for a Course Demo
Website: Visit JustAcademy
1. Introduction to Bitwise Operators in Python
Bitwise operators are special operators in Python that perform operations on the individual bits of integer values. Computers represent numbers internally using binary digits, called bits. Each bit can have one of two values: 0 or 1. Bitwise operators compare, combine, invert, or shift these bits to produce a result.
Unlike arithmetic operators, which perform calculations such as addition and multiplication, bitwise operators manipulate the binary representation of integers. They are useful in low-level programming, embedded systems, network protocols, binary data processing, permission flags, hardware-related programming, and certain optimization techniques.
Python provides six primary bitwise operators: AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>).
Example
a = 10
b = 4
print(a & b)
print(a | b)
print(a ^ b)
Output:
0
14
14
These results are obtained by converting the numbers to binary and applying the relevant operation to each bit position.
2. Learning Objectives
After studying this topic, learners should be able to:
- Understand binary numbers and how integers can be represented in binary.
- Explain the purpose of bitwise operators in Python.
- Use the bitwise AND, OR, XOR, and NOT operators.
- Understand left-shift and right-shift operations.
- Use Python's
bin() function to inspect binary representations.
- Distinguish bitwise operators from logical operators.
- Apply bitwise operations to flags, masks, and permission values.
- Use compound bitwise assignment operators.
- Recognize common mistakes involving operator precedence and negative integers.
- Build practical programs that use bitwise operations.
3. Understanding Binary Numbers
Binary is a number system that uses only two digits: 0 and 1. The decimal number system uses base 10, whereas the binary number system uses base 2.
Each position in a binary number represents a power of 2. Starting from the right, the place values are 1, 2, 4, 8, 16, 32, and so on.
| Binary Position |
Power of 2 |
Decimal Value |
| Rightmost |
20 |
1 |
| Second from right |
21 |
2 |
| Third from right |
22 |
4 |
| Fourth from right |
23 |
8 |
| Fifth from right |
24 |
16 |
| Sixth from right |
25 |
32 |
Example: Converting Decimal to Binary
The decimal number 10 is represented in binary as 1010.
This means:
Binary: 1010
Place: 8421
Calculation:
1 × 8 = 8
0 × 4 = 0
1 × 2 = 2
0 × 1 = 0
Total = 8 + 2 = 10
Using Python to Display Binary Numbers
Python provides the built-in bin() function to convert an integer into a string containing its binary representation.
print(bin(5))
print(bin(10))
print(bin(15))
print(bin(20))
Output:
0b101
0b1010
0b1111
0b10100
The prefix 0b indicates that the displayed number is in binary notation.
4. Overview of Bitwise Operators
| Operator |
Name |
Purpose |
Example |
Result |
& |
Bitwise AND |
Produces 1 where both corresponding bits are 1. |
10 & 4 |
0 |
| |
Bitwise OR |
Produces 1 where either corresponding bit is 1. |
10 | 4 |
14 |
^ |
Bitwise XOR |
Produces 1 where corresponding bits are different. |
10 ^ 4 |
14 |
~ |
Bitwise NOT |
Inverts the integer's bits according to Python's integer rules. |
~10 |
-11 |
<< |
Left shift |
Shifts bits to the left. |
5 << 1 |
10 |
>> |
Right shift |
Shifts bits to the right. |
10 >> 1 |
5 |
5. Bitwise AND Operator (&)
The bitwise AND operator compares corresponding bits of two integers. A result bit is 1 only when both input bits are 1. If either input bit is 0, the result bit is 0.
AND Truth Table
| Bit A |
Bit B |
A & B |
| 0 |
0 |
0 |
| 0 |
1 |
0 |
| 1 |
0 |
0 |
| 1 |
1 |
1 |
Example 1: Basic AND Operation
a = 10
b = 4
print(a & b)
Binary calculation:
a = 10 = 1010
b = 4 = 0100
----
AND result 0000
Output:
0
There are no positions in which both numbers contain a 1, so the result is zero.
Example 2: AND with Overlapping Bits
a = 12
b = 10
print(a & b)
print(bin(a))
print(bin(b))
print(bin(a & b))
Output:
8
0b1100
0b1010
0b1000
The binary representation of 12 is 1100, and 10 is 1010. Only the third bit from the right is 1 in both values, giving the result 1000, which equals 8.
Example 3: Checking Whether a Bit Is Set
AND is often used with a bit mask to check whether a particular bit is enabled.
number = 10
mask = 2
if number & mask:
print("The selected bit is set")
else:
print("The selected bit is not set")
Output:
The selected bit is set
The mask 2 has its second bit from the right set. Since that bit is also set in 10, the AND result is nonzero.
6. Bitwise OR Operator (|)
The bitwise OR operator compares corresponding bits of two integers. A result bit is 1 if at least one of the input bits is 1. The result is 0 only when both input bits are zero.
OR Truth Table
| Bit A |
Bit B |
A | B |
| 0 |
0 |
0 |
| 0 |
1 |
1 |
| 1 |
0 |
1 |
| 1 |
1 |
1 |
Example 1: Basic OR Operation
a = 10
b = 4
print(a | b)
Binary calculation:
a = 10 = 1010
b = 4 = 0100
----
OR result 1110
Output:
14
Example 2: Combining Bit Flags
OR is useful when multiple options are represented by separate bit flags. Each flag can represent a permission or configuration option.
READ = 1 # 001
WRITE = 2 # 010
EXECUTE = 4 # 100
permissions = READ | WRITE
print(permissions)
print(bin(permissions))
Output:
3
0b11
The values 1, 2, and 4 represent different bit positions. Combining READ and WRITE with OR produces 3, which has both corresponding bits set.
Example 3: Enabling a Flag Without Clearing Other Flags
permissions = 1
WRITE = 2
permissions |= WRITE
print(permissions)
Output:
3
The compound assignment operator |= enables the WRITE bit while preserving the bits that were already set.
7. Bitwise XOR Operator (^)
The bitwise XOR operator means exclusive OR. It produces a result bit of 1 when the corresponding input bits are different. When both bits are the same, the result is 0.
XOR Truth Table
| Bit A |
Bit B |
A ^ B |
| 0 |
0 |
0 |
| 0 |
1 |
1 |
| 1 |
0 |
1 |
| 1 |
1 |
0 |
Example 1: Basic XOR Operation
a = 10
b = 4
print(a ^ b)
Binary calculation:
a = 10 = 1010
b = 4 = 0100
----
XOR result 1110
Output:
14
Example 2: Comparing Different Bit Positions
a = 12
b = 10
print(a ^ b)
print(bin(a ^ b))
Output:
6
0b110
The binary values are 1100 and 1010. The differing bit positions produce 0110, which equals 6.
Example 3: Toggling a Bit
XOR can toggle a selected bit. If that bit is 0, XOR with a mask containing 1 at that position changes it to 1. If it is already 1, XOR changes it to 0.
number = 10
mask = 2
number ^= mask
print(number)
print(bin(number))
Output:
8
0b1000
The second bit from the right was set in 10. XOR with 2 toggles that bit off, changing 1010 to 1000.
Important XOR Properties
x ^ 0 returns x.
x ^ x returns 0.
(x ^ y) ^ y returns x.
- XOR is useful for toggling flags and identifying differences between bit patterns.
8. Bitwise NOT Operator (~)
The bitwise NOT operator inverts the bits of an integer according to Python's integer model. Unlike AND, OR, and XOR, NOT is a unary operator, which means it operates on one operand.
For Python integers, the result follows the identity:
~x == -x - 1
Example 1: Applying NOT to a Positive Integer
number = 10
print(~number)
Output:
-11
This may appear surprising if you expect an inversion of only four visible bits. Python integers have arbitrary precision, and bitwise operations on negative integers follow an infinite-sign-extension model. The formula ~x == -x - 1 explains the result.
Example 2: Applying NOT to Other Values
print(~0)
print(~1)
print(~5)
print(~(-5))
Output:
-1
-2
-6
4
Example 3: Verifying the NOT Formula
number = 7
print(~number)
print(-number - 1)
print(~number == -number - 1)
Output:
-8
-8
True
For beginners, the most reliable way to understand Python's bitwise NOT is to remember that it produces -x - 1, rather than assuming a fixed-width integer representation.
9. Left Shift Operator (<<)
The left shift operator moves the bits of an integer to the left by a specified number of positions. For nonnegative integers, this is equivalent to multiplying the value by a power of 2.
For nonnegative integer x and shift count n:
x << n == x * (2 ** n)
Example 1: Shifting Left by One Position
number = 5
print(number << 1)
print(bin(number))
print(bin(number << 1))
Output:
10
0b101
0b1010
The binary representation changes from 101 to 1010, which doubles the value from 5 to 10.
Example 2: Shifting Left by Two Positions
number = 3
result = number << 2
print(result)
Output:
12
Shifting left by two positions multiplies 3 by 4, producing 12.
Example 3: Calculating Powers of Two
print(1 << 0)
print(1 << 1)
print(1 << 2)
print(1 << 3)
print(1 << 4)
Output:
1
2
4
8
16
This works because shifting the binary value 1 left by n positions gives the integer value 2 ** n.
10. Right Shift Operator (>>)
The right shift operator moves the bits of an integer to the right by a specified number of positions. For Python integers, right shifting by n positions is equivalent to floor division by 2 ** n.
x >> n == x // (2 ** n)
Example 1: Shifting Right by One Position
number = 10
print(number >> 1)
print(bin(number))
print(bin(number >> 1))
Output:
5
0b1010
0b101
The binary value 1010 becomes 101, so the decimal result is 5.
Example 2: Shifting Right by Two Positions
number = 20
result = number >> 2
print(result)
Output:
5
Shifting right by two positions divides 20 by 4 using floor division, producing 5.
Example 3: Right Shift with a Negative Integer
print(-9 >> 1)
print(-9 // 2)
Output:
-5
-5
Python right shift follows floor division semantics, so negative values may not behave like truncation toward zero.
11. Difference Between Bitwise and Logical Operators
Bitwise operators and logical operators may look similar, but they serve different purposes. Bitwise operators work on individual bits, while logical operators evaluate truth values and control Boolean expressions.
| Feature |
Bitwise Operators |
Logical Operators |
| Main operators |
&, |, ^, ~ |
and, or, not |
| Purpose |
Manipulate individual bits. |
Combine or invert truth values. |
| Typical use |
Bit masks, flags, binary data. |
Conditions and program decisions. |
| Example |
5 & 3 returns 1. |
True and False returns False. |
| Short-circuit behavior |
Bitwise operations evaluate the required operands. |
and and or can skip evaluation of the second operand. |
Example
a = 5
b = 3
print(a & b)
print(a and b)
Output:
1
3
The expression a & b performs a bitwise AND operation. The expression a and b is a logical operation that returns one of its operands based on truth-value evaluation; it does not necessarily return a Boolean value.
12. Bitwise Compound Assignment Operators
Python provides compound assignment forms for bitwise operations. They perform the specified operation and assign the result back to the target.
| Operator |
Meaning |
Equivalent expression |
&= |
Bitwise AND and assign |
x = x & y |
|= |
Bitwise OR and assign |
x = x | y |
^= |
Bitwise XOR and assign |
x = x ^ y |
| |
Left shift |
|
<<= |
Left shift and assign |
x = x << y |
>>= |
Right shift and assign |
x = x >> y |
Example 1: AND Assignment
number = 14
number &= 10
print(number)
Output:
10
Example 2: OR Assignment
number = 8
number |= 3
print(number)
Output:
11
Example 3: XOR Assignment
number = 15
number ^= 6
print(number)
Output:
9
Example 4: Left and Right Shift Assignment
number = 4
number <<= 2
print(number)
number >>= 1
print(number)
Output:
16
8
13. Using Bit Masks
A bit mask is an integer used to select, test, enable, disable, or toggle specific bits in another integer. Bit masks are common in permission systems, configuration flags, protocol fields, and compact data representations.
A convenient way to create a mask for bit position n is:
mask = 1 << n
Bit positions are counted from zero on the right. For example, bit position 0 represents the value 1, position 1 represents 2, position 2 represents 4, and position 3 represents 8.
| Bit Position |
Mask Expression |
Decimal Mask |
Binary |
| 0 |
1 << 0 |
1 |
0001 |
| 1 |
1 << 1 |
2 |
0010 |
| 2 |
1 << 2 |
4 |
0100 |
| 3 |
1 << 3 |
8 |
1000 |
14. Checking Whether a Bit Is Set
To check whether a particular bit is enabled, combine the number with a mask using bitwise AND. If the result is nonzero, the selected bit is set. Otherwise, it is not set.
Example
number = 10
position = 1
mask = 1 << position
if number & mask:
print("Bit is set")
else:
print("Bit is not set")
Output:
Bit is set
The number 10 is binary 1010. Bit position 1 has the value 2 and is set in this representation.
Reusable Function
def is_bit_set(number, position):
mask = 1 << position
return (number & mask) != 0
print(is_bit_set(10, 1))
print(is_bit_set(10, 0))
Output:
True
False
For an application that accepts arbitrary positions from users, validate that the position is a nonnegative integer.
15. Setting, Clearing, and Toggling Bits
Bit masks can perform three common operations: setting a bit to 1, clearing a bit to 0, and toggling a bit between 0 and 1.
Setting a Bit
Use bitwise OR to set a selected bit without changing the other bits.
number = 8
position = 1
mask = 1 << position
number |= mask
print(number)
print(bin(number))
Output:
10
0b1010
Clearing a Bit
Use AND with the complement of a mask to clear a selected bit.
number = 10
position = 1
mask = 1 << position
number &= ~mask
print(number)
print(bin(number))
Output:
8
0b1000
Toggling a Bit
Use XOR to switch a selected bit from 0 to 1 or from 1 to 0.
number = 8
position = 1
mask = 1 << position
number ^= mask
print(number)
print(bin(number))
Output:
10
0b1010
| Operation |
Expression |
Purpose |
| Test |
number & mask |
Check whether a bit is set. |
| Set |
number |= mask |
Set the selected bit to 1. |
| Clear |
number &= ~mask |
Set the selected bit to 0. |
| Toggle |
number ^= mask |
Invert the selected bit. |
16. Using Bitwise Operators for Permissions
Bitwise flags allow several Boolean options to be stored in a single integer. Each option is assigned a distinct power of two, allowing flags to be combined without overlapping their bit positions.
Example: Permission System
READ = 1 # 001
WRITE = 2 # 010
EXECUTE = 4 # 100
permissions = READ | WRITE
print("Permissions:", permissions)
if permissions & READ:
print("Read permission enabled")
if permissions & WRITE:
print("Write permission enabled")
if permissions & EXECUTE:
print("Execute permission enabled")
Output:
Permissions: 3
Read permission enabled
Write permission enabled
The permission value 3 represents the combination of READ and WRITE. EXECUTE is not enabled, so its condition is false.
Adding and Removing Permissions
READ = 1
WRITE = 2
EXECUTE = 4
permissions = READ | WRITE
# Add execute permission
permissions |= EXECUTE
print(permissions)
# Remove write permission
permissions &= ~WRITE
print(permissions)
Output:
7
5
After adding EXECUTE, all three flags are enabled. Removing WRITE leaves READ and EXECUTE enabled.
17. Bitwise Operator Precedence
When an expression contains multiple operators, Python follows operator precedence rules to determine which operation happens first. Bitwise operators have different precedence levels.
| Relative Priority |
Operator Category |
Examples |
| Higher |
Arithmetic operations |
+, -, * |
| |
Shifting operations |
<<, >> |
| |
Bitwise AND |
& |
| |
Bitwise XOR |
^ |
| Lower |
Bitwise OR |
| |
| Lower still |
Comparisons |
==, <, > |
| |
Logical NOT, AND, OR |
not, and, or |
Example 1: AND Before OR
result = 5 | 3 & 1
print(result)
Output:
5
Bitwise AND has higher precedence than bitwise OR, so Python evaluates 3 & 1 first. The result is 1, and then 5 | 1 produces 5.
Example 2: Using Parentheses for Clarity
a = 5
b = 3
c = 1
result = (a | b) & c
print(result)
Output:
1
Parentheses make the intended order explicit. When working with masks and flags, parentheses can prevent subtle logic errors.
18. Bitwise Operators with Negative Integers
Python integers can represent arbitrarily large positive and negative values. Bitwise operations on negative integers follow Python's integer semantics, which are consistent with an infinite two's-complement-style sign extension.
As a result, negative values may behave differently from examples that assume a fixed number of bits, such as exactly 8 or 16 bits.
Example
print(-5 & 3)
print(-5 | 3)
print(-5 ^ 3)
print(~(-5))
Output:
3
-5
-8
4
These results follow Python's rules for bitwise operations on signed integers. Do not assume that Python automatically limits an integer to 8, 16, or 32 bits.
Working with a Fixed Number of Bits
When a task specifically requires an unsigned 8-bit result, you can use a mask such as 0xFF to retain only the lowest eight bits.
number = -5
eight_bit_value = number & 0xFF
print(eight_bit_value)
print(bin(eight_bit_value))
Output:
251
0b11111011
The mask 0xFF is hexadecimal for 255, or binary 11111111. Applying AND retains only the lowest eight bits of the integer's representation.
19. Common Errors and Troubleshooting
| Problem |
Cause |
Solution |
Using and instead of & |
Confusing logical operations with bitwise operations. |
Use & when manipulating individual bits. |
Using or instead of | |
Confusing logical OR with bitwise OR. |
Use | to combine bit flags. |
Using ^ for exponentiation |
Assuming the caret symbol means power in Python. |
Use ** for exponentiation; ^ means bitwise XOR. |
Unexpected result from ~x |
Assuming the integer has a fixed number of bits. |
Remember that Python follows ~x == -x - 1. |
| Invalid operand types |
Bitwise operators generally require integers or compatible custom objects. |
Convert suitable inputs to integers and validate them. |
| Unexpected mask result |
The mask targets the wrong bit position. |
Remember that bit positions start at zero from the right. |
| Negative shift count |
The shift count is less than zero. |
Validate that the shift count is nonnegative. |
| Unexpected expression result |
Operator precedence was misunderstood. |
Use parentheses to show the intended operation order. |
Example: Validating a Shift Count
number = 8
shift_count = int(input("Enter shift count: "))
if shift_count < 0:
print("Shift count cannot be negative.")
else:
print(number << shift_count)
In this example, a negative shift count is rejected before the operation is performed.
20. Practical Example: Extracting and Checking Flags
Consider an application that stores three settings in a single integer: notifications, dark mode, and automatic updates.
Program
NOTIFICATIONS = 1
DARK_MODE = 2
AUTO_UPDATE = 4
settings = NOTIFICATIONS | AUTO_UPDATE
print("Settings value:", settings)
if settings & NOTIFICATIONS:
print("Notifications: ON")
else:
print("Notifications: OFF")
if settings & DARK_MODE:
print("Dark mode: ON")
else:
print("Dark mode: OFF")
if settings & AUTO_UPDATE:
print("Automatic updates: ON")
else:
print("Automatic updates: OFF")
Output:
Settings value: 5
Notifications: ON
Dark mode: OFF
Automatic updates: ON
This approach is useful when an application needs to represent several independent on/off settings compactly. Each flag should use a distinct power of two.
21. Practical Example: Displaying the Binary Representation
The following program displays the binary forms of two integers and the results of their bitwise operations.
a = int(input("Enter the first integer: "))
b = int(input("Enter the second integer: "))
print("First number:", a, bin(a))
print("Second number:", b, bin(b))
print("AND:", a & b, bin(a & b))
print("OR:", a | b, bin(a | b))
print("XOR:", a ^ b, bin(a ^ b))
Sample Input:
Enter the first integer: 12
Enter the second integer: 10
Output:
First number: 12 0b1100
Second number: 10 0b1010
AND: 8 0b1000
OR: 14 0b1110
XOR: 6 0b110
This program is helpful for understanding how the binary representation changes during each operation.
22. Practical Example: Converting an Integer into Binary Digits
Python's bin() function already provides binary conversion. However, understanding how to inspect individual bits is useful when learning bitwise programming.
Program: Display the Lowest Four Bits
number = 13
for position in range(3, -1, -1):
bit = (number >> position) & 1
print(bit, end="")
print()
Output:
1101
The program shifts each target bit to the rightmost position and uses AND with 1 to extract it. The loop displays the lowest four bits from left to right.
23. Best Practices for Using Bitwise Operators
- Understand binary representation before using bitwise operations in complex programs.
- Use descriptive constants for flags instead of scattering unexplained numeric masks throughout the code.
- Use powers of two for independent flags so each flag occupies a unique bit position.
- Use parentheses to clarify expressions that combine multiple bitwise operators.
- Remember that
^ means XOR, not exponentiation.
- Remember that
~x returns -x - 1 in Python.
- Validate bit positions and shift counts when they come from external input.
- Be explicit about fixed-width requirements when processing binary data or hardware values.
- Prefer ordinary Boolean operators for logical conditions rather than using bitwise operators unnecessarily.
- Write small tests for setting, clearing, toggling, and checking bits.
- Use
bin() when debugging binary calculations.
- Document the meaning of each bit flag in permission and configuration systems.
24. Practice Exercises
Beginner-Level Exercises
- Convert the decimal numbers 6, 9, and 15 into binary using
bin().
- Calculate the bitwise AND of 7 and 3.
- Calculate the bitwise OR of 5 and 2.
- Calculate the bitwise XOR of 12 and 10.
- Find the results of
~0, ~3, and ~10.
- Shift the number 8 left by two positions.
- Shift the number 32 right by three positions.
Intermediate-Level Exercises
- Write a program that checks whether bit position 2 is set in a given integer.
- Write a function that sets a specified bit in a number.
- Write a function that clears a specified bit in a number.
- Write a function that toggles a specified bit using XOR.
- Create a permission system with READ, WRITE, and EXECUTE flags.
- Use
&=, |=, and ^= to update a number.
Advanced-Level Exercises
- Write a program that displays the lowest eight bits of a nonnegative integer.
- Determine whether an integer is a power of two using bitwise AND and appropriate input validation.
- Build a configuration manager that enables and disables several settings using flags.
- Write a program that extracts a selected group of bits from an integer using shifts and a mask.
- Compare logical operators and bitwise operators with suitable examples.
25. Mini Project: Bitwise Permission Manager
Project Objective: Create a simple permission manager that stores access permissions in one integer and allows users to inspect, enable, or remove permissions.
Project Code
READ = 1
WRITE = 2
EXECUTE = 4
permissions = READ
print("Initial permissions:", permissions)
# Enable WRITE permission
permissions |= WRITE
print("After enabling WRITE:", permissions)
# Enable EXECUTE permission
permissions |= EXECUTE
print("After enabling EXECUTE:", permissions)
# Check permissions
print("Can read:", bool(permissions & READ))
print("Can write:", bool(permissions & WRITE))
print("Can execute:", bool(permissions & EXECUTE))
# Remove WRITE permission
permissions &= ~WRITE
print("After removing WRITE:", permissions)
print("Can read:", bool(permissions & READ))
print("Can write:", bool(permissions & WRITE))
print("Can execute:", bool(permissions & EXECUTE))
Sample Output
Initial permissions: 1
After enabling WRITE: 3
After enabling EXECUTE: 7
Can read: True
Can write: True
Can execute: True
After removing WRITE: 5
Can read: True
Can write: False
Can execute: True
Project Concepts Used
- Bitwise OR for enabling permissions.
- Bitwise AND for checking permissions.
- Bitwise NOT for creating a mask that clears a selected bit.
- Compound assignment operators for updating the permission value.
- Boolean conversion for displaying permission status clearly.
26. Interview Questions and Answers
Q1. What are bitwise operators in Python?
Answer: Bitwise operators perform operations on the bits of integers. Python provides AND (&), OR (|), XOR (^), NOT (~), left shift (<<), and right shift (>>).
Q2. What is the difference between bitwise AND and bitwise OR?
Answer: AND returns 1 only when both corresponding bits are 1. OR returns 1 when at least one corresponding bit is 1.
Q3. What does the XOR operator do?
Answer: XOR returns 1 when corresponding bits differ and 0 when they are the same. It is useful for toggling bits and identifying differences between bit patterns.
Q4. What is the result of 10 & 4?
Answer: The result is 0. The binary values are 1010 and 0100, and no corresponding position contains 1 in both values.
Q5. What is the result of 10 | 4?
Answer: The result is 14. In binary, 1010 OR 0100 produces 1110.
Q6. What is the difference between ^ and **?
Answer: The ^ operator performs bitwise XOR, whereas ** performs exponentiation. For example, 2 ** 3 returns 8.
Q7. What does the bitwise NOT operator return for an integer?
Answer: In Python, ~x returns -x - 1. For example, ~5 returns -6.
Q8. What is the purpose of the left shift operator?
Answer: The left shift operator moves bits to the left. For a nonnegative integer, shifting left by n positions is equivalent to multiplying by 2 ** n.
Q9. What is the purpose of the right shift operator?
Answer: The right shift operator moves bits to the right. Python defines right shift by n positions as floor division by 2 ** n.
Q10. What is a bit mask?
Answer: A bit mask is an integer used to select, test, set, clear, or toggle specific bits. Masks are frequently used for permissions and configuration flags.
Q11. How can you check whether a particular bit is set?
Answer: Create a mask using 1 << position and apply bitwise AND. If the result is nonzero, the selected bit is set.
Q12. How do you set a bit without changing the other bits?
Answer: Use bitwise OR with a mask: number |= (1 << position).
Q13. How do you clear a selected bit?
Answer: Use AND with the complement of a mask: number &= ~(1 << position).
Q14. How do you toggle a selected bit?
Answer: Use XOR with a mask: number ^= (1 << position).
Q15. What is the difference between bitwise and logical AND?
Answer: Bitwise AND (&) operates on corresponding bits. Logical AND (and) evaluates truth values and can short-circuit, returning one of its operands rather than necessarily returning a Boolean value.
27. Quick Revision Checklist
- Binary: A base-2 number system that uses 0 and 1.
- AND (
&): Sets a result bit when both input bits are 1.
- OR (
|): Sets a result bit when either input bit is 1.
- XOR (
^): Sets a result bit when the input bits differ.
- NOT (
~): Inverts an integer according to Python's integer rules; ~x == -x - 1.
- Left shift (
<<): Moves bits left; for nonnegative integers this multiplies by a power of two.
- Right shift (
>>): Moves bits right and follows floor division semantics.
- Bit mask: An integer used to target specific bits.
- Set a bit: Use OR with a mask.
- Clear a bit: Use AND with the complement of a mask.
- Toggle a bit: Use XOR with a mask.
- Check a bit: Use AND and test whether the result is nonzero.
- Binary inspection: Use
bin() to display an integer in binary notation.
- Precedence: Use parentheses to make complicated expressions clear.
28. Conclusion
Bitwise operators are important Python tools for working directly with the binary representation of integers. The AND, OR, XOR, and NOT operators manipulate bits, while the left-shift and right-shift operators move bits between positions.
These operators are especially useful for bit masks, permission flags, configuration settings, binary data processing, and low-level programming tasks. Learning how to test, set, clear, and toggle bits provides a foundation for solving more advanced programming problems.
Practice the examples, exercises, and permission manager project to strengthen your understanding of bitwise operations and their practical applications.
Continue learning with the Python Training Course at JustAcademy, register for a course demo, or visit the JustAcademy homepage.