Java Reference
In-Depth Information
15.19. Shift Operators
The operators
<<
(left shift),
>>
(signed right shift), and
>>>
(unsigned right shift) are called
the
shift operators
. The left-hand operand of a shift operator is the value to be shifted; the
right-hand operand specifies the shift distance.
ShiftExpression
:
AdditiveExpression
ShiftExpression
<<
AdditiveExpression
ShiftExpression
>>
AdditiveExpression
ShiftExpression
>>>
AdditiveExpression
The shift operators are syntactically left-associative (they group left-to-right).
It is a compile-time error if the type of each of the operands of a shift operator, after unary
numeric promotion, is not a primitive integral type.
The type of the shift expression is the promoted type of the left-hand operand.
If the promoted type of the left-hand operand is
int
, only the five lowest-order bits of the
right-hand operand are used as the shift distance. It is as if the right-hand operand were sub-
The shift distance actually used is therefore always in the range
0
to
31
, inclusive.
If the promoted type of the left-hand operand is
long
, then only the six lowest-order bits
of the right-hand operand are used as the shift distance. It is as if the right-hand operand
(
0b111111
). The shift distance actually used is therefore always in the range
0
to
63
, inclus-
ive.
At run time, shift operations are performed on the two's-complement integer representation
of the value of the left operand.
The value of
n
<<
s
is
n
left-shifted
s
bit positions; this is equivalent (even if overflow oc-
curs) to multiplication by two to the power
s
.
The value of
n
>>
s
is
n
right-shifted
s
bit positions with sign-extension. The resulting value
is ?
n
/ 2
s
?. For non-negative values of
n
, this is equivalent to truncating integer division,
as computed by the integer division operator
/
, by two to the power
s
.