Shift operators in Java
<<, >> (sign-extending) and >>> (zero-fill).
1 << 31 is a huge negative number. 1 << 32 is... 1. Shift operators hide some of Java's strangest results.Left shift multiplies by 2ⁿ
x << n moves every bit n places to the left and fills the gap with zeros. Each place doubles the value, as long as no bits fall off the top.
3 << 1 // 110 = 6
3 << 2 // 1100 = 12
1 << 10 // 1024>> keeps the sign
x >> n moves bits to the right and copies the sign bit into the gap, so negative numbers stay negative. It divides by 2ⁿ, rounding down.
20 >> 2 // 5
-16 >> 2 // -4Your turn
What does this print?
System.out.println(5 << 3);
System.out.println(40 >> 3);40 515 138 5
Show the answer
5 << 3 is 5 × 2³ = 40, and 40 >> 3 is 40 / 2³ = 5.
>>> fills with zeros
>>> (unsigned right shift) fills the gap with zeros, clearing the sign bit, so a negative number turns positive. There's no <<<: left shifts always fill with zeros anyway.
// -16 is 0xFFFFFFF0
-16 >>> 28 // 1111 = 15Your turn
-1 is all 32 bits set to 1. What does this print?
System.out.println(-8 >> 1);
System.out.println(-1 >>> 28);-4 154 15-4 -1
Show the answer
>> keeps the sign: -8 >> 1 is -4. >>> brings in zeros: shifting thirty-two 1-bits right by 28 leaves four 1s, 1111 = 15.
Shifting by 32 or more
For an int, only the lowest 5 bits of the distance are used, so the distance is effectively taken mod 32. 1 << 32 is really 1 << 0, which is 1. Need 2³²? Use a long: 1L << 32 (longs use the distance mod 64).
1 << 32 // 1, not 4294967296
1L << 32 // 4294967296In real projects
Shifts power graphics, hashing and network code: (rgb >> 16) & 0xFF extracts the red channel from a color. Java's own HashMap spreads hash codes with h ^ (h >>> 16).
Key takeaways
- x << n is x × 2ⁿ (if nothing overflows)
- >> keeps the sign: -16 >> 2 is -4
- >>> fills with zeros: negative becomes positive
- int shifts use distance % 32: 1 << 32 is 1
C has no >>> operator. Java added it because Java has no unsigned integer types, so it needed a separate way to shift right while filling with zeros.
Practice questions
What does this print?
System.out.println(3 << 2);
System.out.println(20 >> 2);- 12 5
- 6 10
- 12 10
- 32 5
Check your answer
12 5. 3 << 2 is 3 × 4 = 12, and 20 >> 2 is 20 / 4 = 5.
What does this print?
System.out.println(-16 >> 2);
System.out.println(-16 >>> 28);- -4 -1
- -4 15
- 4 15
- -4 1
Check your answer
-4 15. >> keeps the sign, so -16 >> 2 is -4. -16 is 0xFFFFFFF0; >>> 28 brings in zeros and leaves the top four 1-bits, 1111, which is 15.