|
|
|
1000 Java Tips ebook
|
|
 

Free "1000 Java Tips" eBook is here! It is huge collection of big and small Java
programming articles and tips. Please take your copy here.
Take your copy of free "Java Technology Screensaver"!. |
|
The Java Lesson 7: Bitwise operations with good examples, click here!
|
JavaFAQ Home » Java Lessons by Jon Huhtala

The Java Lesson 7
Bitwise operations: overview with detailed examples
Overview
Bitwise operations act upon
individual bits within integer data. They are used to perform the logical
operations AND, OR, and XOR (eXclusive OR), complementing (reversing all bits),
and shifting (sliding bits to the left or right).
Logical bitwise operations
-
Use the standard boolean
operators (&, |, and ^) to act upon two integer values. The
short-circuit boolean operators (&& and ||) are not used for bitwise operations and will result in a
compile error if attempted.
-
Produce an integer result (of
size int or larger) that
is the logical AND, OR, or XOR of two operands. The rules for these operations
are as follows:
| Operation |
Rule |
|
& |
If both corresponding operand bits are
"on" the result bit is "on" |
|
| |
If either corresponding operand bit is
"on" the result bit is "on" |
|
^ |
If corresponding operand bits are
different the result bit is
"on" |
For example, if
byte x = 5; // Binary value:
0000 0101 Hex value: 05 byte y = 9; // Binary
value: 0000 1001 Hex value: 09 byte z;
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 |
|
z =
(byte)(x & y); |
0000
0001 |
01 |
01 |
|
z =
(byte)(x | y); |
0000
1101 |
0D |
13 |
|
z =
(byte)(x ^ y); |
0000
1100 |
0C |
12 | Example: The following program can be run to test logical
bitwise 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
logical bitwise 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!
|
|
|