Bitwise Operator Techniques
Advanced Bitwise Operations
Bit Shifting Techniques
graph LR
A[Left Shift <<] --> B[Multiplication]
A --> C[Value Doubling]
D[Right Shift >>] --> E[Division]
D --> F[Value Halving]
Left Shift (<<)
public class BitShifting {
public static void main(String[] args) {
int x = 5; // Binary: 0101
int result = x << 2; // Shifts 2 positions left
System.out.println(result); // Output: 20
}
}
Right Shift (>>)
public class BitShifting {
public static void main(String[] args) {
int x = 20; // Binary: 10100
int result = x >> 2; // Shifts 2 positions right
System.out.println(result); // Output: 5
}
}
Bit Manipulation Patterns
Common Bit Manipulation Techniques
Technique |
Operation |
Example |
Use Case |
Set Bit |
x |= (1 << n) |
Set nth bit |
Flag management |
Clear Bit |
x &= ~(1 << n) |
Clear nth bit |
Bit flag reset |
Toggle Bit |
x ^= (1 << n) |
Flip nth bit |
State toggling |
Practical Bit Manipulation
public class BitManipulation {
// Check if a number is even or odd
public static boolean isEven(int num) {
return (num & 1) == 0;
}
// Swap two numbers without temp variable
public static void swapNumbers(int a, int b) {
a = a ^ b;
b = a ^ b;
a = a ^ b;
}
public static void main(String[] args) {
System.out.println(isEven(10)); // true
System.out.println(isEven(7)); // false
}
}
Advanced Bit Manipulation Techniques
Bit Masking
public class BitMasking {
// Check specific bit
public static boolean isBitSet(int num, int position) {
return (num & (1 << position)) != 0;
}
public static void main(String[] args) {
int value = 42; // Binary: 101010
System.out.println(isBitSet(value, 3)); // true
System.out.println(isBitSet(value, 2)); // false
}
}
- Bitwise operations are faster than arithmetic operations
- Useful in low-level system programming
- Critical for embedded systems and performance-critical applications
At LabEx, we emphasize the importance of understanding these advanced bit manipulation techniques for efficient Java programming.