Java Reference
In-Depth Information
If this value were shifted once to the left, you would get the following:
0 1 0 1 1 0 1 0
The number is 90, which just happens to be twice 45. Because it is a binary
shift to the left, this is equivalent to multiplying by two.
Similarly, the right-shift operators shift the binary digits to the right. The
only difference between the two right-shift operators is that one is signed (>>)
and the other is unsigned (>>>). The signed right-shift brings in the sign bit on
the right, whereas the unsigned right-shift always brings in a 0 on the right, no
matter what the sign bit is.
For example, the following is 45 represented in binary format:
0 0 1 0 1 1 0 1
The most significant bit is a 0, so shifting to the right using >> or >>> pro-
duces the same result:
0 0 0 1 0 1 1 0
If the sign bit is a 1, as in the following binary representation of -4, the shift
operators do make a difference:
1 1 1 1 1 1 0 0
Shifting this value to the right using >> produces the following, which is the
value -2:
1 1 1 1 1 1 1 0
Shifting to the right using >> is equivalent to dividing the number by 2.
Shifting -4 to the right using >>> results in the following, which has no mean-
ingful mathematical result:
0 1 1 1 1 1 1 0
The following ShiftDemo program demonstrates the use of the shift opera-
tors. Study the program and try to determine its output, which is shown in
Figure 2.7.
Search WWH ::




Custom Search