The Java Lesson 7: Bitwise operations with good examples, click here! Page 3
JavaFAQ Home » Java Lessons by Jon Huhtala
The Java Lesson 7
Bitwise operations: overview with detailed examples
1. Logical bitwise operations
2. The complement operator
3. Bitwise shift operations
4. Bitwise assignment operations andr review questions
Bitwise shift operations

Shift the bits of the first
integer operand the number of bits specified by the second integer operand.
The operator used determines the direction of the shift and whether the sign
of the number is to be maintained.

The maximum number of bit
positions that can be shifted is 31 bits. If the second operand specifies a
shift value greater than 31, only its rightmost 5 bits will be used as the
shift value. In other words, a shift factor of 32 is the same as a shift
factor of 0.

Use the << (left shift), >> (signed right shift),
and >>>
(unsigned right shift) operators. The rules for these operations are as
follows:
Operation 
Rule 
<< 
Shifts the first operand to the left the
number of bits specified by the rightmost 5 bits of the second
operand. The loworder bit of the first operand is replaced with
binary 0. 
>> 
Shifts the first operand to the right the
number of bits specified by the rightmost 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 rightmost 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.
Printer Friendly Page
Send to a Friend
..
Search here again if you need more info!

