Java Reference
In-Depth Information
What is the result of
13 << 35
? You might have guessed zero. However, this is not true. In fact, only 32 bits are
used to represent
13
, because
13
is considered as
int
literal and
int
occupies 32 bits. You can shift all bits to the
left only by
31
bits in an
int
. If the left-hand operand of bitwise left shift operator (<<) is
int
, only five lower order
bits' value of the right-hand operand is used as the number of bits to shift. For example, in
13 << 35
, the right-hand
operand (
35
) can be represented in binary as follows:
00000000000000000000000000100011
The five lower order bits in 35 are 00011, which is equal to 3. Therefore, when you write
13 << 35
, it is equivalent
to writing
13 << 3
. For all positive right-hand operands of the bitwise left shift operator, you can take the modulus
of the right-hand operand with 32, which would be the final number of bits to shift. Therefore,
13 << 35
can be
considered as
13 << (35 % 32)
which is the same as
13 << 3
. If the left-hand operand is long, the value of the first six
lower order bits of the right-hand operand is used as the number of bits to shift.
long val = 13;
long result;
result = val << 35;
Since
val
is a
long
variable, the six lower order bits of
35
, which are
100011
, will be used as the number to shift.
Figure
4-2
shows the steps used to compute
13 >> 4
and
-13 >> 4
.
Figure 4-2.
Computing 13 >> 4 and -13 >> 4
The bitwise signed right shift operator (
>>
) shifts all the bits to the right by the number specified as its right-hand
operand. If the most significant digit of the left-hand operand is 1 (for negative numbers), all higher order bits are
filled with 1s after the shift operation. If the most significant bit is 0 (for positive numbers), all higher order bits are
filled with 0s. Because the sign bit after right shift operation (
>>
) remains the same, it is called a signed right shift
operator. For example,
13 >> 4
results in zero, as depicted in Figure
4-2
. Also note that in the case of
-13 >> 4
all four
higher order bits are filled with 1s because in
-13
, the most significant digit is 1. The result of
-13 >> 4
is
-1
.