Bitwise Operators in Java
Contents
The ~ Operator (NOT)
The & Operator (AND)
The | Operator (OR)
The ^ Operator (XOR)
The << Operator (LSH/left-shift)
The >> Operator (SRSH/signed right-shift)
The >>> Operator (URSH/unsigned right-shift)
Back to Top
The ~ Operator (NOT)
General Usage:
result = ~operand;
The ~ operator is called an unary operator, because it takes
only one argument. The arguments of an operator are also called the operands.
Other operators, for instance, the & operator, require two operands,
thus they are called binary operators. Operators that require three operands
are called ternary operators...
By using ~, you can calculate the bitwise complement of a value. The
bitwise complement of a value is the value with the opposite bit states:
1100 1110 1001 1101 is the bitwise complement of
0011 0001 0110 0010
Example:
public class ExampleBitwiseNOT {
public static void main(String[] args) {
int value = 0x87654321;
System.out.println("Value : "
+ Integer.toBinaryString(value));
//calculates the bitwise complement
int NOT_value = ~value;
System.out.println("Bitwise Complement: "
+ Integer.toBinaryString(NOT_value));
}
}
/*
The output of this example will be:
Value : 10000111011001010100001100100001
Bitwise Complement: 1111000100110101011110011011110
*/
|
Back to Top
The & Operator (AND)
General Usage:
result = operand1 & operand2;
As you can see, the & operator is a binary operator, because it
takes two operands.
This operator is used to combine two values by ANDing their bits at each position.
The bit state of the resulting value at a specific position is only 1,
if the states of the bits at that position of operand1 AND
operand2 are 1:
The result of
1100 1110 1001 1101
& 1101 0100 0111 1001
is
1100 0100 0001 1001
.
Example:
public class ExampleBitwiseAND {
public static void main(String[] args) {
int operand1 = 0x87654321;
int operand2 = 0xFEDCBA98;
System.out.println("Operand1 : "
+ Integer.toBinaryString(operand1));
System.out.println("Operand2 : "
+ Integer.toBinaryString(operand2));
//calculates the bitwise AND result
int result = operand1 & operand2;
System.out.println("Result : "
+ Integer.toBinaryString(result));
}
}
/*
The output of this example will be:
Operand1 : 10000111011001010100001100100001
Operand2 : 11111110110111001011101010011000
Result : 10000110010001000000001000000000
*/
|
Back to Top
to be continued....