1. The Hook (The "Byte-Sized" Intro)
In a Nutshell: Bitwise operators work at the binary levelโmanipulating individual bits (0s and 1s). They're ultra-fast and power permissions, flags, graphics, and encryption.
When Linux checks file permissions (rwxr-xr-x), it uses bitwise operators on a single number! 755 in octal = 111 101 101 in binary = read/write/execute flags.
2. Conceptual Clarity (The "Simple" Tier)
๐ก The Analogy: Light Switches
Think of bits as light switches (0=OFF, 1=ON):
&(AND) โ Both switches must be ON|(OR) โ At least one switch ON^(XOR) โ Exactly one switch ON (flip if different)~(NOT) โ Flip all switches<<(Left shift) โ Add zeros on right (multiply by 2)>>(Right shift) โ Remove bits on right (divide by 2)
Visual Map
3. Technical Mastery (The "Deep Dive")
๐ Formal Definition
| Operator | Name | Description | Example |
|---|---|---|---|
& | AND | 1 if both bits are 1 | 5 & 3 = 1 |
| | OR | 1 if either bit is 1 | 5 | 3 = 7 |
^ | XOR | 1 if bits differ | 5 ^ 3 = 6 |
~ | NOT | Flip all bits | ~5 = -6 |
<< | Left shift | Shift left, fill with 0s | 5 << 1 = 10 |
>> | Right shift | Shift right (signed) | 5 >> 1 = 2 |
>>> | Unsigned right shift | Shift right, fill with 0s | 5 >>> 1 = 2 |
The "Why" Paragraph
Bitwise operators are absurdly fastโCPUs execute them in 1 clock cycle. They're essential for:
- Permissions: Unix file modes (
rwx= 3 bits) - Flags: Enable/disable features without booleans
- Graphics: Color manipulation (RGB values)
- Cryptography: XOR encryption
- Performance:
x & 1(check even/odd) is 10x faster thanx % 2
Bit Manipulation Examples
AND (&): 1101 OR (|): 1101 XOR (^): 1101
1011 1011 1011
---- ---- ----
1001 1111 0110
NOT (~): 1101 Shift<<: 101 Shift>>: 1010
---- ร 2 = รท 2 =
0010 1010 01014. Interactive & Applied Code
Complete Example
public class BitwiseDemo {
public static void main(String[] args) {
int a = 5; // Binary: 0101
int b = 3; // Binary: 0011
System.out.println("a = " + a + " (" + Integer.toBinaryString(a) + ")");
System.out.println("b = " + b + " (" + Integer.toBinaryString(b) + ")");
// AND: Both bits must be 1
System.out.println("\na & b = " + (a & b)); // 1 (0001)
// OR: At least one bit is 1
System.out.println("a | b = " + (a | b)); // 7 (0111)
// XOR: Bits differ
System.out.println("a ^ b = " + (a ^ b)); // 6 (0110)
// NOT: Flip all bits
System.out.println("~a = " + (~a)); // -6 (two's complement)
// Left shift: Multiply by 2^n
System.out.println("\na << 1 = " + (a << 1)); // 10 (multiply by 2)
System.out.println("a << 2 = " + (a << 2)); // 20 (multiply by 4)
// Right shift: Divide by 2^n
System.out.println("a >> 1 = " + (a >> 1)); // 2 (divide by 2)
// Real-world: Check even/odd (FAST!)
int num = 17;
if ((num & 1) == 0) {
System.out.println("\n" + num + " is even");
} else {
System.out.println("\n" + num + " is odd"); // โ
}
// Real-world: Permission flags
final int READ = 1 << 0; // 0001 = 1
final int WRITE = 1 << 1; // 0010 = 2
final int EXECUTE = 1 << 2; // 0100 = 4
int permissions = READ | WRITE; // 0011 = 3
System.out.println("\n๐ Permissions:");
System.out.println("Can read: " + ((permissions & READ) != 0)); // true
System.out.println("Can write: " + ((permissions & WRITE) != 0)); // true
System.out.println("Can execute: " + ((permissions & EXECUTE) != 0));// false
}
}โ ๏ธ Common Mistakes
Mistake #1: Using & for boolean logic
if (x > 0 & y > 0) { // โ No short-circuit (checks both)
// Use &&: if (x > 0 && y > 0)Mistake #2: Confusion with NOT (~)
int x = 5;
System.out.println(~x); // โ Prints -6, not 0!
// ~5 flips all 32 bits: 00000101 โ 11111010 (two's complement = -6)Mistake #3: Shift overflow
int x = 1 << 31; // โ Creates negative number (sign bit set)
// Use long: long x = 1L << 31;5. The Comparison & Decision Layer
Bitwise vs Logical
| Feature | & (Bitwise) | && (Logical) |
|---|---|---|
| Works on | Integers (bit-by-bit) | Booleans |
| Short-circuit | No | Yes |
| Use case | Bit manipulation | Boolean logic |
| Example | flags & MASK | x != null && x.isValid() |
Common Bit Tricks
// Check if power of 2
boolean isPowerOf2 = (n & (n - 1)) == 0 && n != 0;
// Swap without temp variable
a = a ^ b;
b = a ^ b;
a = a ^ b;
// Toggle bit at position i
x = x ^ (1 << i);
// Set bit at position i
x = x | (1 << i);
// Clear bit at position i
x = x & ~(1 << i);6. The "Interview Corner" (The Edge)
๐ Interview Question #1: "How do you check if a number is a power of 2 using bitwise?"
Answer: (n & (n - 1)) == 0 && n != 0
- Example:
8 & 7 = 1000 & 0111 = 0000โ - Non-power:
6 & 5 = 0110 & 0101 = 0100โ
๐ Interview Question #2: "What's the difference between >> and >>>?"
Answer:
>>: Signed shift (preserves sign bit, fills with sign)>>>: Unsigned shift (fills with 0s)
-8 >> 1 = -4 (11111000 โ 11111100)
-8 >>> 1 = 2147483644 (fills with 0s)๐ Interview Question #3: "Count number of set bits (1s) in an integer?"
Answer:
int countSetBits(int n) {
int count = 0;
while (n != 0) {
count += (n & 1); // Check last bit
n >>>= 1; // Shift right
}
return count;
}
// Or use: Integer.bitCount(n)๐ก Pro Tips
Tip #1: Multiply/divide by powers of 2 with shifts
x << 3 // Multiply by 8 (2^3)
x >> 2 // Divide by 4 (2^2)Tip #2: Use bit flags for multiple booleans
// Instead of: boolean flag1, flag2, flag3...
int flags = 0;
final int FLAG_A = 1 << 0;
final int FLAG_B = 1 << 1;
flags |= FLAG_A; // Set flag
if ((flags & FLAG_A) != 0) { } // Check flagTip #3: XOR for encryption (simple)
int encrypt = data ^ key;
int decrypt = encrypt ^ key; // Original data!๐ Real-World Examples
File Permissions: chmod 755 = rwxr-xr-x (bitwise flags)
Feature Toggles: if ((features & DARK_MODE) != 0)
Image Processing: RGB color manipulation
๐ Key Takeaways
โ
Bitwise operators work on binary (0s and 1s)
โ
Ultra-fast: 1 CPU cycle
โ
Use & for bits, && for booleans
โ
Shifts multiply/divide by powers of 2
โ
Perfect for flags, permissions, optimization
Final Tip: Bitwise is powerful but cryptic. Use for performance-critical code, comment well!