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

  1. Binary of 12: 1 1 0 0
  2. Binary of 7: 0 1 1 1
  3. Apply AND:
    • 1 & 0 = 0
    • 1 & 1 = 1
    • 0 & 1 = 0
    • 0 & 1 = 0

Result: 0 1 0 0 (which is 4 in decimal).

Example B: Bitwise OR (|)

Problem: Calculate 12 | 7

  1. Binary of 12: 1 1 0 0
  2. Binary of 7: 0 1 1 1
  3. Apply OR:
    • 1 | 0 = 1
    • 1 | 1 = 1
    • 0 | 1 = 1
    • 0 | 1 = 1

Result: 1 1 1 1 (which is 15 in decimal).

Example C: Bitwise XOR (^)

Problem: Calculate 12 ^ 7

  1. Binary of 12: 1 1 0 0
  2. Binary of 7: 0 1 1 1
  3. Apply XOR (1 if bits are different):
    • 1 ^ 0 = 1
    • 1 ^ 1 = 0
    • 0 ^ 1 = 1
    • 0 ^ 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 << n is equivalent to x × 2n.
    5 << 1 → Binary 101 becomes 1010 (10).
  • Right Shift (>>): x >> n is equivalent to x // 2n.
    20 >> 2 → Binary 10100 becomes 101 (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: ~x is 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:

  1. Setting Permissions: (e.g., Linux file permissions like Read/Write/Execute).
  2. Compression Algorithms: Packing multiple boolean flags into a single integer to save memory.
  3. Graphics and Cryptography: Manipulating pixel colors or encrypting data at the byte level.
Tip: You can use the bin() function in Python to see the binary representation of any number: bin(12) returns '0b1100'.

Practice Quiz