Java Reference
In-Depth Information
The Shift Operators
In Java it is possible to shift the bits that make up a value to the left or to the right by a
specified amount. Java defines the three bit-shift operators shown here:
<< Left shift
>> Right shift
>>> Unsigned right shift
The general forms for these operators are shown here:
value << num-bits
value >> num-bits
value >>> num-bits
Here, value is the value being shifted by the number of bit positions specified by num-bits .
Each left shift causes all bits within the specified value to be shifted left one position and
a 0 bit to be brought in on the right. Each right shift shifts all bits to the right one position
and preserves the sign bit. As you may know, negative numbers are usually represented by
setting the high-order bit of an integer value to 1, and this is the approach used by Java.
Thus, if the value being shifted is negative, each right shift brings in a 1 on the left. If the
value is positive, each right shift brings in a 0 on the left.
In addition to the sign bit, there is something else to be aware of when right shifting.
Java uses two's complement to represent negative values. In this approach negative values
are stored by first reversing the bits in the value and then adding 1. Thus, the byte value for
-1 in binary is 1111 1111. Right shifting this value will always produce -1!
If you don't want to preserve the sign bit when shifting right, you can use an unsigned
right shift (>>>), which always brings in a 0 on the left. For this reason, the >>> is also
called the zero-fill right shift. You will use the unsigned right shift when shifting bit pat-
terns, such as status codes, that do not represent integers.
For all of the shifts, the bits shifted out are lost. Thus, a shift is not a rotate, and there is
no way to retrieve a bit that has been shifted out.
Shown next is a program that graphically illustrates the effect of a left and right shift.
Here, an integer is given an initial value of 1, which means that its low-order bit is set.
Then, a series of eight shifts are performed on the integer. After each shift, the lower 8 bits
Search WWH ::




Custom Search