Bitwise Operations
Why manipulate bits?
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:
- Controlling options in an application (each bit representing a parameter)
- Data compression and encryption
- Processing images, sounds or signals
- Microcontrollers and embedded systems
These operations are fast, memory-efficient, and often used in systems where resources are limited.
How does it work?
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
Main bitwise operations
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 |
Binary representation
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
Concrete example: options stored in a byte
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
Check if an option is activated
state = 0b00000110 # Wi-Fi and Bluetooth enabled
wifi = 0b00000100
if state & wifi:
print("Wi-Fi enabled")
Activate an option (ex: airplane mode)
state |= 0b00001000 # Activates bit 3
Deactivate an option (ex: Bluetooth)
state &= ~0b00000010 # Sets bit 1 to 0
Toggle an option (XOR)
state ^= 0b00000100 # If Wi-Fi was enabled, it's disabled, and vice versa
Summary
- Bitwise operations act directly on the binary representation of integers
- They allow manipulating data in a fine, efficient and fast way
- The most common operators are
&
,|
,^
,~
,<<
,>>
- We can use bits to store and manage multiple states in a single integer variable
These concepts are useful in algorithms, electronics, and in all systems where memory optimization and execution speed are important.