| Operation |
Rule |
|
<< |
Shifts the first operand to the left the
number of bits specified by the right-most 5 bits of the second
operand. The low-order bit of the first operand is replaced with
binary 0. |
|
>> |
Shifts the first operand to the right the
number of bits specified by the right-most 5 bits of the second
operand. The sign bit of the first operand is shifted and replaced
with its original value (so the sign is maintained). |
|
>>> |
Shifts the first operand to the right the
number of bits specified by the right-most 5 bits of the second
operand. The sign bit of the first operand is shifted and replaced
with binary 0. |
For example, if
byte x = 7; // Binary value:
0000 0111 Hex value: 07
byte y;
this table shows the result of
executing three unrelated statements. The cast is needed in order to store the
int value that results
from the operation.
| Statement |
Binary Result |
Hexadecimal |
Decimal |
|
y =
(byte)(x >> 2); |
0000
0001 |
01 |
01 |
|
y =
(byte)(x << 2); |
0001
1100 |
1C |
28 |
|
y
= (byte)(x >>> 3); |
0000
0000 |
00 |
00 |
Example: The following program can be run to test bitwise shift
operations.
public class App
{
public static void main(String[] args)
{
// Variables to be read from the
user
int first;
int
second;
// Prompt for and read the two
integers
System.out.print("First integer:
");
first = Keyboard.readInt();
System.out.print("Second integer: ");
second =
Keyboard.readInt();
// Display the results of
bitwise shift operations
System.out.println("
"
+ first + " << " + second + " = " +
(first << second));
System.out.println(" " +
first + " >> " + second + " = " +
(first >> second));
System.out.println(" " +
first + " >>> " + second + " = "
+
(first >>> second));
}
}
Notes:
-
Program results are displayed in decimal.
To really understand what is happening, work out the equivalent binary and
hexadecimal values.
-
Be sure to run the program several times
with different integer values.