Bitwise Operators
1. Think in Bits (beginner)
Bitwise ops work on binary digits: & (both 1), | (either 1), ^ (different), ~ (flip), << >> >>> (shift). Used for flags, fast ×2/÷2, hardware masks.
2. Table with 4-bit Examples (memorize)
5 = 0101, 3 = 0011
5 & 3 = 0001 = 1 (both 1)
5 | 3 = 0111 = 7 (either 1)
5 ^ 3 = 0110 = 6 (different)
~5 = ...1010 = -6 (flip all + two's complement!)
5 << 1 = 1010 = 10 (×2!) 5 >> 1 = 0010 = 2 (÷2!)
-8 >>> 2 = big positive (0 fills left, no sign!)
| Op | Name | Beginner use |
|---|---|---|
& | ^ |
AND/OR/XOR bits | masks, flags |
~ |
NOT (flip) | ~x = -x-1 |
<< |
left shift (×2ⁿ) | x<<2 = ×4 fast |
>> |
right shift (÷2ⁿ, keep sign) | x>>1 = ÷2 |
>>> |
unsigned shift (0 fill) | positive result always |
3. Code — Flags + Fast Tricks
int READ = 4; // 100
int WRITE = 2; // 010
int perm = READ | WRITE; // 110 = 6 (both flags on!)
System.out.println((perm & READ) != 0); // true (has read?)
int x = 5;
System.out.println(x << 2); // 20 (×4)
System.out.println(x % 2 == (x & 1)); // true: &1 checks odd/even fast!
4. Traps
>>keeps sign (-8>>1 = -4),>>>fills 0 (-8>>>1 = huge +ve).&on ints is bitwise (not logical!) — context decides: booleans → logical, ints → bits.- Precedence: shifts below
+:1<<2+1=1<<3= 8 (not 5!).
5. Exam Points
- Compute
5&3,5|3,5^3,5<<1— 5 marks, very frequent. >>vs>>>on negative — 3-5 marks, favourite trap.- Flag/mask program — 3 marks, frequent.