|
|
|
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! Page 2
|
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
The complement operator
For example, if
byte a = 17; // Binary value: 0001
0001 Hex value: 11 byte b;
after executing the
statement
b = (byte) ~a;
variable b will have a value of -18 (because 0001 0001 reverses to 1110
1110). Once again, the cast is needed in order to store the int value that results from the
operation.
Example: The following program can be run to test complement
operations.
public class App
{ public static void main(String[] args)
{
// Variable to be read from the
user
int number;
//
Prompt for and read an integer value
System.out.print("Integer: "); number =
Keyboard.readInt();
// Display the result of
complementing the number
System.out.println("
~" + number + " = " + ~number);
} }
Notes:
-
Again, program results are displayed in
decimal so work them out in binary to understand what is happening.
-
The sign of a number changes when it is
complemented due to the sign bit being reversed.
-
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!
|
|
|