Table of Contents
TogglePython bitwise operators are normally used to perform bitwise operations on integer-type objects. However, instead of treating the object as a whole, it is treated as a string of bits. Different operations are done on each bit in the string.
Python has six bitwise operators – &, |, ^, ~, << and >>. All these operators (except ~) are binary in nature, in the sense they operate on two operands. Each operand is a binary digit (bit) 1 or 0.
# 8-bit representation examples
60 → 00111100
13 → 00001101
~60 → 11000011 (Two's complement)
# Masking application example
a = 0b11001100
mask = 0b11110000
result = a & mask # 0b11000000 → 192
print(f"Masked value: {result}")
# Combining permissions example
READ = 0b1000
WRITE = 0b0100
EXECUTE = 0b0010
full_access = READ | WRITE | EXECUTE # 0b1110 → 14
print(f"Full access code: {full_access}")
# Data encryption example
data = 0b10101010
key = 0b11110000
encrypted = data ^ key # 0b01011010
decrypted = encrypted ^ key # Original data
print(f"Decrypted: {bin(decrypted)}")
# Memory optimization example
MAX_INT = ~(1 << 31) # For 32-bit systems
print(f"Maximum 32-bit integer: {MAX_INT}")
# Efficient calculations example
kilobytes = 1024
megabytes = kilobytes << 10 # 1048576
gigabytes = megabytes << 10 # 1073741824
print(f"GB: {gigabytes}")
# Bitwise vs Arithmetic operations
import timeit
print("Multiply:", timeit.timeit('15 * 16'))
print("Shift: ", timeit.timeit('15 << 4'))
