Bitwise Operators (&, |, ^, ~) & Flag Manipulation
1Concept
Bitwise operators work on binary bit representations of integers. AND (&), OR (|), XOR (^), and NOT (~) enable low-level bit flag manipulation and performance optimizations.
2Architecture Diagram
Bitwise AND (&): 1010 & 1100 = 1000 (8) Bitwise OR (|): 1010 | 1100 = 1110 (14) Bitwise XOR (^): 1010 ^ 1100 = 0110 (6)
3Code Example
Core Java
public class BitwiseDemo {
public static void main(String[] args) {
int READ_PERMISSION = 1 << 0; // 1 (0001)
int WRITE_PERMISSION = 1 << 1; // 2 (0010)
int EXEC_PERMISSION = 1 << 2; // 4 (0100)
int userPermissions = READ_PERMISSION | WRITE_PERMISSION;
boolean canWrite = (userPermissions & WRITE_PERMISSION) != 0;
System.out.println("User Permission Mask: " + userPermissions);
System.out.println("Has Write Permission: " + canWrite);
}
}4Expected Output
User Permission Mask: 3 Has Write Permission: true
5Key Takeaways
- ✓Bitwise flags conserve memory by packing multiple boolean flags into a single integer.
- ✓Bitwise XOR (^) swaps two variables without temporary storage: a = a ^ b; b = a ^ b; a = a ^ b;.
- ✓Bitwise NOT (~) flips all binary bits.