Operators in Python | Bitwise Operators | Python Tutorials for Beginners #lec17
3 min read
6 months ago
Published on Apr 21, 2024
This response is partially generated with the help of AI. It may contain inaccuracies.
Table of Contents
Step-by-step tutorial on Bitwise Operators in Python:
-
Understand Bitwise Operators:
- Bitwise operators work on binary numbers or bits in Python.
- The main bitwise operators are bitwise and (&), bitwise or (|), bitwise xor (^), left shift (<<), right shift (>>), and complement or not (~).
-
Working of Bitwise Operators:
- Consider two variables,
a = 5
andb = 4
. - To perform a bitwise operation, convert the numbers into binary representation.
- For example,
a
is101
andb
is100
in binary.
- Consider two variables,
-
Bitwise AND (&) Operator:
a & b
will perform a bitwise AND operation.- In this case,
101 & 100
results in100
, which is equal to 4 in decimal.
-
Bitwise OR (|) Operator:
a | b
will perform a bitwise OR operation.101 | 100
results in101
, which is equal to 5 in decimal.
-
Bitwise XOR (^) Operator:
a ^ b
will perform a bitwise XOR operation.101 ^ 100
results in001
, which is equal to 1 in decimal.
-
Bitwise NOT (~) Operator:
~a
will perform a bitwise NOT operation.~5
results in-6
due to the way negative numbers are stored in memory using two's complement.
-
Left Shift (<<) Operator:
a << 2
will perform a left shift operation by 2 bits.5 << 2
results in10100
, which is equal to 20 in decimal.
-
Right Shift (>>) Operator:
a >> 2
will perform a right shift operation by 2 bits.5 >> 2
results in1
, which is equal to 1 in decimal.
-
Practical Exercise:
- Create variables
a = 5
andb = 4
. - Perform bitwise operations like
a & b
,a | b
,a ^ b
,~a
,a << 2
, anda >> 2
. - Calculate the results manually first and then verify them by running the code.
- Create variables
-
Further Exploration:
- Experiment with different values and bitwise operations to deepen your understanding.
- Try out operations like left shifting and right shifting with various values to see their effects.
-
Conclusion:
- By practicing with bitwise operators in Python, you can gain a better understanding of how they work and their applications in programming.
-
Next Steps:
- Stay tuned for the next video to learn about the identity and membership operators in Python.
By following these steps, you can grasp the concepts and practical applications of bitwise operators in Python effectively. Happy coding!