Bitwise Operators

Carson West

Operators

Bitwise Operators

Bitwise operators work directly on the individual bits of integers. They are rarely used in typical Python programming but are essential for low-level programming, working with hardware, or specific optimization scenarios.

Types of Bitwise Operators:

Examples:

a = 10  # Binary: 1010
b = 4   # Binary: 0100

print(a & b)  # Output: 0 (Binary: 0000)
print(a | b)  # Output: 14 (Binary: 1110)
print(a ^ b)  # Output: 14 (Binary: 1110)
print(~a)   # Output: -11 (depends on system's representation of negative numbers)
print(a << 2) # Output: 40 (Binary: 101000)
print(a >> 1) # Output: 5  (Binary: 0101)

Twos Complement (This needs a separate explanation)

Binary Representation of Numbers (This also needs a separate explanation)

Use Cases:

Important Note: Bitwise operators only work on integers. Applying them to other data types will result in a TypeError.