Understanding Bitwise Operators
Bitwise operators allow direct manipulation of individual bits of a number. These operators work at the binary level and are commonly used in low-level programming, performance optimizations, graphics, hardware control, and even simple algorithm tricks.
Why Bitwise?
Bitwise operations are extremely fast and can simplify complex operations. They're often used when memory or performance is critical.
Common Bitwise Operators
- AND (&): Sets each bit to 1 if both bits are 1
- OR (|): Sets each bit to 1 if one of two bits is 1
- XOR (^): Sets each bit to 1 if only one of two bits is 1
- NOT (~): Inverts all bits
- LEFT SHIFT (<<): Shifts bits to the left, adds 0s on the right
- RIGHT SHIFT (>>): Shifts bits to the right, discards bits on the right
Example 1: Bitwise AND
Let’s take two numbers: 6 (which is 110 in binary) and 3 (011).
A = 6 // binary: 110
B = 3 // binary: 011
C = A & B // performs bitwise AND
print(C)
Output:
2
Explanation:
Bitwise AND compares each bit. Only if both bits are 1, the result is 1.
110
AND
011
=
010 → which is 2
Question:
What happens if we AND any number with 0?
Answer:
It always returns 0, because 0 AND anything is 0.
Example 2: Bitwise OR
A = 6 // binary: 110
B = 3 // binary: 011
C = A | B // performs bitwise OR
print(C)
Output:
7
Explanation:
110
OR
011
=
111 → which is 7
Example 3: Bitwise XOR
A = 6 // binary: 110
B = 3 // binary: 011
C = A ^ B // performs bitwise XOR
print(C)
Output:
5
Explanation:
XOR returns 1 only when the bits differ.
110
XOR
011
=
101 → which is 5
Example 4: Bitwise NOT
A = 6 // binary: 00000110
C = ~A // flips all bits
print(C)
Output:
-7 (in two's complement systems)
Explanation:
Bitwise NOT inverts all bits. In two’s complement, ~6 becomes -7 because of how negative numbers are represented in binary.
Example 5: Left and Right Shift
A = 4 // binary: 100
B = A << 1 // shift left by 1 bit
C = A >> 1 // shift right by 1 bit
print(B)
print(C)
Output:
8 2
Explanation:
Left shift multiplies by 2, right shift divides by 2.
Real-World Use-Cases
- Setting Flags: You can use bitwise OR to set specific bits (used in hardware control).
- Toggling Bits: XOR is used to flip a bit without affecting others.
- Checking Even/Odd: (num & 1) checks the last bit to determine if a number is odd.
- Swapping Numbers: Bitwise XOR trick to swap two values without a temp variable.
- Optimization: Multiply/divide by powers of 2 using shift operators.
Mini Exercise
Try this:
A = 10
print(A & 1) // What does this return?
Answer:
It returns 0, which means 10 is even (last bit is 0).
Summary
Bitwise operators are powerful tools that can optimize performance and simplify logic in many scenarios. Although they might seem complex initially, practicing with binary representations makes them intuitive over time.