Sub topic 14
Signed and Unsigned Shifts
A bit is a digit that is either 0 or 1. Java stores whole numbers as patterns of bits. A shift operator moves those bits left or right. Shifts can help you work with values stored as individual bits, such as on-or-off settings.
An int uses 32 bits. A long uses 64 bits. The examples below use int.
Three shift operators
| Operator | What it does |
|---|---|
| `<<` | Shifts bits left and fills the empty places on the right with zeros. |
| `>>` | Shifts bits right and fills the empty places on the left with copies of the sign bit. |
| `>>>` | Shifts bits right and fills the empty places on the left with zeros. |
The sign bit is the leftmost bit of a signed whole number. It is 0 for a nonnegative number and 1 for a negative number.
Bits that move past either end are lost. For example, shifting the bits of 10 right by one place gives 5:
10: 00000000 00000000 00000000 00001010
5: 00000000 00000000 00000000 00000101For a nonnegative number, >> and >>> produce the same result. Both fill the left side with zeros.
Worked example: a negative number
For negative numbers, >> and >>> differ. Here is the 32-bit pattern for -8, followed by each result after a one-place shift:
-8: 11111111 11111111 11111111 11111000
-8 >> 1: 11111111 11111111 11111111 11111100
-8 >>> 1: 01111111 11111111 11111111 11111100The signed shift, >>, copies the 1 from the sign bit. Its result is -4. The unsigned shift, >>>, fills the leftmost place with 0. Its result is 2147483644.
Save this complete program as ShiftDemo.java:
public class ShiftDemo {
public static void main(String[] args) {
System.out.println(5 << 1); // 10
System.out.println(10 >> 1); // 5
System.out.println(-8 >> 1); // -4
System.out.println(-8 >>> 1); // 2147483644
}
}Compile and run it:
javac ShiftDemo.java
java ShiftDemoUseful limits
Shifting left by one often doubles a number, but that is not guaranteed. Bits can be lost, including a bit that changes the sign. For example, 1 << 31 is -2147483648.
A signed right shift by one often resembles division by 2. For a negative number, though, it rounds down: -7 >> 1 is -4, while -7 / 2 is -3.
Java also limits the effective shift distance. For an int, the distance repeats every 32 places, so 1 << 32 is the same as 1 << 0: the result is 1. For a long, the distance repeats every 64 places.
Practice
Exercise
What are the results of 12 >> 1 and 12 >>> 1?
Show answer
Both are 6. Since 12 is nonnegative, both operators fill the left side with zeros.
Exercise
What are the results of -7 >> 1 and 1 << 32?
Show answer
They are -4 and 1. The first shift rounds down; the second has an effective distance of zero.