Bitwise operations allow manipulating binary values directly, that is, bit by bit. They are widely used in low-level computing, but also in concrete situations like:
Each integer is represented by a sequence of bits (0 or 1). Bitwise operations compare or modify these bits individually.
Example:
# Binary representation
x = 5 # 0b0101
y = 3 # 0b0011
| Operation | Symbol | Effect | Example |
|---|---|---|---|
| Logical AND | & | 1 if both bits are 1 | 0b0101 & 0b0011 = 0b0001 |
| Logical OR | | | 1 if at least one of the two bits is 1 | 0b0101 | 0b0011 = 0b0111 |
| Exclusive OR (XOR) | ^ | 1 if only one of the two bits is 1 | 0b0101 ^ 0b0011 = 0b0110 |
| Logical NOT | ~ | Inverts all bits (two's complement) | ~0b00000000 = 0b11111111 |
| Left shift | << | Shifts bits to the left (multiplies) | 0b00000001 << 1 = 0b00000010 |
| Right shift | >> | Shifts bits to the right (divides) | 0b00000100 >> 1 = 0b00000010 |
An integer can be displayed in binary with the format(n, '08b') function, which displays the number on 8 bits. Example:
state = 0b00000110
print(format(state, '08b')) # Displays 00000110
Suppose a program stores several options in a single byte. Each bit represents an activated (1) or deactivated (0) option.
Bit 0: Sound enabled
Bit 1: Bluetooth enabled
Bit 2: Wi-Fi enabled
Bit 3: Airplane mode enabled
Bit 4: Notifications enabled
state = 0b00000110 # Wi-Fi and Bluetooth enabled
wifi = 0b00000100
if state & wifi:
print("Wi-Fi enabled")
state |= 0b00001000 # Activates bit 3
state &= ~0b00000010 # Sets bit 1 to 0
state ^= 0b00000100 # If Wi-Fi was enabled, it's disabled, and vice versa
&, |, ^, ~, <<, >>These concepts are useful in algorithms, electronics, and in all systems where memory optimization and execution speed are important.