Lesson Completion
Back to course

Bitwise Operators: Manipulating Bits Like a Hacker

Beginner
12 minutesโ˜…4.9Java

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

graph TD Bits["Binary: 1101 & 1011"] --> AND["& = 1001<br/>(AND each bit)"] Bits2["Binary: 1101 | 1011"] --> OR["| = 1111<br/>(OR each bit)"] Bits3["Binary: 1101 ^ 1011"] --> XOR["^ = 0110<br/>(XOR each bit)"] Bits4["5 << 1"] --> Shift["10<br/>(5 * 2)"] style AND fill:#2E7D32 style OR fill:#F57C00 style XOR fill:#1976D2

3. Technical Mastery (The "Deep Dive")

๐Ÿ“˜ Formal Definition

OperatorNameDescriptionExample
&AND1 if both bits are 15 & 3 = 1
|OR1 if either bit is 15 | 3 = 7
^XOR1 if bits differ5 ^ 3 = 6
~NOTFlip all bits~5 = -6
<<Left shiftShift left, fill with 0s5 << 1 = 10
>>Right shiftShift right (signed)5 >> 1 = 2
>>>Unsigned right shiftShift right, fill with 0s5 >>> 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 than x % 2

Bit Manipulation Examples

text
AND (&): 1101 OR (|): 1101 XOR (^): 1101 1011 1011 1011 ---- ---- ---- 1001 1111 0110 NOT (~): 1101 Shift<<: 101 Shift>>: 1010 ---- ร— 2 = รท 2 = 0010 1010 0101

4. Interactive & Applied Code

Complete Example

java
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

java
if (x > 0 & y > 0) { // โŒ No short-circuit (checks both) // Use &&: if (x > 0 && y > 0)

Mistake #2: Confusion with NOT (~)

java
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

java
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 onIntegers (bit-by-bit)Booleans
Short-circuitNoYes
Use caseBit manipulationBoolean logic
Exampleflags & MASKx != null && x.isValid()

Common Bit Tricks

java
// 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)
java
-8 >> 1 = -4 (11111000 โ†’ 11111100) -8 >>> 1 = 2147483644 (fills with 0s)

๐Ÿ† Interview Question #3: "Count number of set bits (1s) in an integer?"

Answer:

java
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

java
x << 3 // Multiply by 8 (2^3) x >> 2 // Divide by 4 (2^2)

Tip #2: Use bit flags for multiple booleans

java
// 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 flag

Tip #3: XOR for encryption (simple)

java
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!

Topics Covered

Java FundamentalsOperators

Tags

#java#operators#expressions#arithmetic#logical#beginner-friendly

Last Updated

2025-02-01