Saturday, 21 December 2024

Python Bitwise Operators: A Comprehensive Guide

 Bitwise operators in Python allow you to perform operations at the bit level. These operators are essential for tasks such as low-level programming, cryptography, and working with hardware. In this guide, we will explore all Python bitwise operators with clear examples to help you master their usage.


1. What Are Bitwise Operators?

Bitwise operators work on binary representations of numbers (bits). These operators directly manipulate the bits and return results based on bitwise operations. Python provides the following bitwise operators:

OperatorNameDescription
&Bitwise ANDSets each bit to 1 if both bits are 1
|Bitwise OR
Sets each bit to 1 if at least one bit is 1


^Bitwise XORSets each bit to 1 if only one bit is 1
~Bitwise NOTInverts all the bits
<<Left ShiftShifts bits to the left
>>Right ShiftShifts bits to the right

2. Understanding Binary Representation

Before diving into examples, it is crucial to understand how numbers are represented in binary.

For example:

  • 5 in binary is 0101

  • 3 in binary is 0011


3. **Bitwise AND (&)

The & operator compares each bit of two numbers. A bit is set to 1 if both corresponding bits are 1.

Syntax:

result = a & b

Example:

a = 5  # Binary: 0101
b = 3  # Binary: 0011
result = a & b  # Binary: 0001
print(result)  # Output: 1

Truth Table:

Bit 1Bit 2Result
000
010
100
111

4. **Bitwise OR (|)

The | operator compares each bit of two numbers. A bit is set to 1 if at least one of the corresponding bits is 1.

Syntax:

result = a | b

Example:

a = 5  # Binary: 0101
b = 3  # Binary: 0011
result = a | b  # Binary: 0111
print(result)  # Output: 7

Truth Table:

Bit 1Bit 2Result
000
011
101
111

5. **Bitwise XOR (^)

The ^ operator compares each bit of two numbers. A bit is set to 1 if the corresponding bits are different.

Syntax:

result = a ^ b

Example:

a = 5  # Binary: 0101
b = 3  # Binary: 0011
result = a ^ b  # Binary: 0110
print(result)  # Output: 6

Truth Table:

Bit 1Bit 2Result
000
011
101
110

6. **Bitwise NOT (~)

The ~ operator inverts all the bits of a number. For positive numbers, it returns the negative value of the number minus one.

Syntax:

result = ~a

Example:

a = 5  # Binary: 0101
result = ~a  # Binary: -0110
print(result)  # Output: -6

Explanation:

In binary, ~5 flips all bits of 0101 to 1010. In two's complement representation, this corresponds to -6.


7. **Left Shift (<<)

The << operator shifts the bits of a number to the left by the specified number of positions. Each left shift doubles the number.

Syntax:

result = a << n

Example:

a = 5  # Binary: 0101
result = a << 2  # Binary: 10100
print(result)  # Output: 20

Explanation:

Shifting 0101 two places to the left gives 10100, which is 20 in decimal.


8. **Right Shift (>>)

The >> operator shifts the bits of a number to the right by the specified number of positions. Each right shift divides the number by two (ignoring the remainder).

Syntax:

result = a >> n

Example:

a = 5  # Binary: 0101
result = a >> 2  # Binary: 0001
print(result)  # Output: 1

Explanation:

Shifting 0101 two places to the right gives 0001, which is 1 in decimal.


9. Combining Bitwise Operators

You can combine bitwise operators to perform complex bit-level operations.

Example:

a = 5  # Binary: 0101
b = 3  # Binary: 0011

# Combining operators
result = (a & b) | (~a)
print(result)  # Output: -2

10. Practical Applications of Bitwise Operators

1. Setting and Clearing Bits

# Setting a bit
number = 0b1010
position = 1
number |= (1 << position)
print(bin(number))  # Output: 0b1011

# Clearing a bit
number &= ~(1 << position)
print(bin(number))  # Output: 0b1010

2. Checking if a Bit is Set

number = 0b1010
position = 2
is_set = (number & (1 << position)) != 0
print(is_set)  # Output: True

3. Swapping Two Numbers Without a Temporary Variable

a = 5
b = 3

a = a ^ b
b = a ^ b
a = a ^ b

print(a, b)  # Output: 3, 5

11. Common Mistakes with Bitwise Operators

Mistake 1: Confusing Bitwise Operators with Logical Operators

a = 5
b = 3
# Incorrect: Using 'and' instead of '&'
result = a and b  # Logical AND, not Bitwise AND
print(result)  # Output: 3

Mistake 2: Ignoring Operator Precedence

result = ~a & b  # Not the same as ~(a & b)

Use parentheses to make the precedence clear.


Conclusion

Bitwise operators are powerful tools in Python for performing low-level operations. They are invaluable in fields like cryptography, network programming, and embedded systems. By mastering these operators, you can write more efficient and optimized code.

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (53) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (932) Python Coding Challenge (358) Python Quiz (23) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses