Java Reference ยท Operators
Java shift operators
Reference for Java shift operators <<, >> and >>>: signed and unsigned right shift, how the shift distance is masked, and typical uses and pitfalls.
The shift operators move the bits of an integer left or right. << shifts left and fills with zeros, which multiplies by a power of two (until overflow). >> is the signed (arithmetic) right shift: it copies the sign bit into the vacated positions, so negative numbers stay negative. >>> is the unsigned (logical) right shift: it always fills with zeros.
The left operand is promoted to int or long. The result type is that promoted type, not the type of the shift distance.
int a = 1 << 4; // 16 int b = -16 >> 2; // -4 int c = -16 >>> 28; // 15
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Syntax
value << distance value >> distance value >>> distance
| Operator | Name | Fill bits |
|---|---|---|
<< |
left shift | zeros on the right |
>> |
signed right shift | copies of the sign bit |
>>> |
unsigned right shift | zeros on the left |
The compound forms <<=, >>= and >>>= also exist.
Usage notes
- Distance is masked. For an
intonly the low 5 bits of the distance are used (x << 32isx); for along, the low 6 bits. A negative distance therefore wraps rather than shifting the other way. - Overflow.
1 << 31isInteger.MIN_VALUE. Shifts do not check for lost bits; useMath.multiplyExactif overflow matters. - Division by shifting rounds toward negative infinity for negative numbers (
-7 >> 1is-4), whereas/truncates toward zero (-7 / 2is-3). Do not replace division with shifts for signed values. >>>onbyteandshortis misleading. The value is promoted tointwith sign extension first, so the result does not behave as an 8-bit unsigned shift. Mask with& 0xFFbefore shifting.- The result type follows the promoted left operand, so
byte << intgives anintand needs a cast to store back into abyte(compound assignment casts automatically). - Prefer readable alternatives (
Math.pow,Integer.rotateLeft,ByteBuffer) unless you really handle bit fields.