Bitwise operators in Python allow you to manipulate individual bits of integers. They are useful for performing bit-level operations such as shifting, AND, OR, XOR, and complement.
The bitwise operators in Python are:
Operator | Description |
---|---|
AND (&) | Performs a bitwise AND operation |
OR (|) | Performs a bitwise OR operation |
XOR (^) | Performs a bitwise XOR operation |
Left Shift (<<) | Shifts the bits to the left |
Right Shift (>>) | Shifts the bits to the right |
Complement (~) | Returns the one’s complement of the number |
2. AND Operator (&)
The AND operator (&
) compares each bit of two operands and returns 1 if both bits are 1; otherwise, it returns 0.
Example
# Example of AND operator
a = 10 # 1010 in binary
b = 3 # 0011 in binary
result = a & b
print(result) # Output: 2
# Explanation: 1010 & 0011 = 0010 (decimal 2)
3. OR Operator (|)
The OR operator (|
) compares each bit of two operands and returns 1 if at least one of the bits is 1.
Example
# Example of OR operator
a = 10 # 1010 in binary
b = 3 # 0011 in binary
result = a | b
print(result) # Output: 11
# Explanation: 1010 | 0011 = 1011 (decimal 11)
4. XOR Operator (^)
The XOR operator (^
) compares each bit of two operands and returns 1 if exactly one of the bits is 1, but not both.
Example
# Example of XOR operator
a = 10 # 1010 in binary
b = 3 # 0011 in binary
result = a ^ b
print(result) # Output: 9
# Explanation: 1010 ^ 0011 = 1001 (decimal 9)
5. Shift Operators
Shift operators move the bits of a number to the left (<<
) or to the right (>>
) by the specified amount.
Left Shift Example
# Example of left shift
a = 5 # 101 in binary
result = a << 2
print(result) # Output: 20
# Explanation: 101 << 2 = 10100 (decimal 20)
Right Shift Example
# Example of right shift
a = 20 # 10100 in binary
result = a >> 2
print(result) # Output: 5
# Explanation: 10100 >> 2 = 101 (decimal 5)
6. Complement Operator (~)
The complement operator (~
) inverts all the bits of a number.
Example
# Example of complement operator
a = 5 # 101 in binary
result = ~a
print(result) # Output: -6
# Explanation: ~101 = -110 (in two's complement, -6 in decimal)
7. Practical Applications
Manipulating Binary Data
Bitwise operators are useful for manipulating binary data, such as encryption, encoding, and optimizing algorithms.
# Example of simple encryption using XOR
message = 0b10101010 # Binary representation of a message
key = 0b11110000 # Encryption key
encrypted_message = message ^ key
print(bin(encrypted_message)) # Output: 0b10111010 (binary representation)