3.3 Bitwise Operator (BT101CO)
Bitwise operators are used to perform operations at the binary level (0s and 1s). While most programming happens at a higher level, bitwise operations are extremely fast and memory-efficient.
1. The Core Bitwise Operators
| Operator | Name | Description |
|---|---|---|
& |
AND | Sets bit to 1 if both bits are 1. |
| |
OR | Sets bit to 1 if one or both bits are 1. |
^ |
XOR | Sets bit to 1 if only one bit is 1 (exclusive OR). |
~ |
NOT | Inverts all bits (1 becomes 0, 0 becomes 1). |
<< |
Left Shift | Shifts bits to the left, filling with 0s from the right. |
>> |
Right Shift | Shifts bits to the right, discarding bits on the right. |
2. Solved Examples
Example A: Bitwise AND (&)
Problem: Calculate 12 & 7
- Binary of 12:
1 1 0 0 - Binary of 7:
0 1 1 1 - Apply AND:
1 & 0 = 01 & 1 = 10 & 1 = 00 & 1 = 0
Result: 0 1 0 0 (which is 4 in decimal).
Example B: Bitwise OR (|)
Problem: Calculate 12 | 7
- Binary of 12:
1 1 0 0 - Binary of 7:
0 1 1 1 - Apply OR:
1 | 0 = 11 | 1 = 10 | 1 = 10 | 1 = 1
Result: 1 1 1 1 (which is 15 in decimal).
Example C: Bitwise XOR (^)
Problem: Calculate 12 ^ 7
- Binary of 12:
1 1 0 0 - Binary of 7:
0 1 1 1 - Apply XOR (1 if bits are different):
1 ^ 0 = 11 ^ 1 = 00 ^ 1 = 10 ^ 1 = 1
Result: 1 0 1 1 (which is 11 in decimal).
3. Bitwise Shift Operators
These move bits like a conveyor belt. They are often used for very fast multiplication or division by powers of 2.
- Left Shift (
<<):x << nis equivalent to x × 2n.5 << 1→ Binary101becomes1010(10). - Right Shift (
>>):x >> nis equivalent to x // 2n.20 >> 2→ Binary10100becomes101(5).
4. Bitwise NOT (~) and Two's Complement
The NOT operator is often confusing because it involves Two's Complement (how computers store negative numbers).
- Formula:
~xis equal to-(x + 1). - Example:
~12- 12 + 1 = 13
- Result: -13.
5. Practical Use Cases
While you might not use these in every script, they are essential for:
- Setting Permissions: (e.g., Linux file permissions like Read/Write/Execute).
- Compression Algorithms: Packing multiple boolean flags into a single integer to save memory.
- Graphics and Cryptography: Manipulating pixel colors or encrypting data at the byte level.
Tip: You can use thebin()function in Python to see the binary representation of any number:bin(12)returns'0b1100'.