Lesson 34.1 · Bit Manipulation
Binary, Two's Complement and the Operators
Java ints are 32-bit two's complement. & | ^ ~ work bit by bit; << shifts left; >> shifts right keeping the sign; >>> shifts right filling with zeros.
14 min
Think of it like this
A row of 32 light switches. Each operator is a rule for combining two rows of switches: & keeps a light on only if both are on, | if either is on, ^ if exactly one is on, ~ flips every switch.
1.Binary numbers
Bit i is worth 2ⁱ: 12 = 8 + 4 = 1100. Two's complement stores negatives as ~x + 1, so −1 is all 32 bits set, the top bit is the sign, and the range is −2³¹ to 2³¹ − 1.
x & y (AND), x | y (OR), x ^ y (XOR), ~x (NOT). x << k multiplies by 2ᵏ (bits fall off the top). x >> k divides by 2ᵏ rounding down, copying the sign bit. x >>> k fills with zeros, treating x as unsigned.
Precedence trap: == binds tighter than &, so x & 1 == 0 doesn't compile; write (x & 1) == 0.
public class Main {
public static void main(String[] args) {
int a = 12, b = 10; // 1100 and 1010
System.out.println("a & b = " + (a & b));
System.out.println("a | b = " + (a | b));
System.out.println("a ^ b = " + (a ^ b));
System.out.println("~a = " + (~a));
System.out.println("a << 1 = " + (a << 1));
System.out.println("a >> 2 = " + (a >> 2));
System.out.println("-8 >> 1 = " + (-8 >> 1));
System.out.println("-8 >>> 28 = " + (-8 >>> 28));
System.out.println("-8 in binary = " + Integer.toBinaryString(-8));
}
}Output
a & b = 8
a | b = 14
a ^ b = 6
~a = -13
a << 1 = 24
a >> 2 = 3
-8 >> 1 = -4
-8 >>> 28 = 15
-8 in binary = 11111111111111111111111111111000Remember
- Two's complement: −x = ~x + 1.
- >> keeps the sign, >>> doesn't.
- Parenthesise bit expressions in comparisons.
Common mistakes
- Using >> on negative numbers when an unsigned shift was intended.
- Shifting by 32 or more (Java uses only the low 5 bits of the shift count).
Words used in this lesson
- Bit
- A single binary digit, 0 or 1.
- Two's complement
- The standard way computers store negative integers: flip all bits and add 1.
- Mask
- An int whose set bits select the positions you care about.