Bitwise operators
Operator
|
Name
|
Example
|
Description
|
|
Expr1 & expr2
|
Bitwise and
|
7 & 5
|
7 = 111
5 = 101
101
|
Answer = 5, 1 if both
bits are 1 else 0.
|
Expr1 & expr2
|
Bitwise and
|
7 | 5
|
7 = 111
5 = 101
111
|
Answer= 7, 0 if both bits
are 0 or else 1.
|
Expr1 | expr2
|
Bitwise xor
|
5 ^ 7
|
7 = 111
5 = 101
010
|
Answer= 2, 1 if odd nos. of
1 present.
|
~expr1
|
Bitwise not
|
~3
|
(~expr
1) will give -4 which is 1100 in 2's complement form due to a signed binary
number.
|
|
Expr1 << expr2
|
Bitwise left shift
|
10 << 3
|
10 * 23
|
Answer=80, Num * 23
|
Expr1 >> expr2
|
Bitwise right shift
|
20>>3
|
20 / 23
|
Answer=2, Num / 23
|
Expr1 >>> expr2
|
Bitwise Unsigned Right
Shift
|
-10 >>>2
|
10 = 1010
|
Answer=2
|
Bitwise Operator
Example
public class Bitwise_Operator
{
public static void main(String
args[])
{
Bitwise_Operator bp=new
Bitwise_Operator();
bp.BitOP();
bp.BitShift();
}
void BitOP()
{
int Num1=25; // 11001
int Num2=5; //binary 00101
System.out.println("Value of Num1 and Num2 is = "+Num1+"
, "+Num2);
System.out.println("Binary value of Num1 is 11001");
System.out.println("Binary
value of Num2 is 00101 ");
System.out.println("\nResult after Bitwise AND
(multiplication)" );
System.out.println("Num1 & Num2 = " + (Num1 & Num2));
System.out.println("\nResult
after Bitwise OR (Addition)" );
System.out.println("Num1 | Num2 = " + (Num1 | Num2));
System.out.println("\nResult after Bitwise Ex-OR" );
System.out.println("Num1 ^ Num2 = " + (Num1 ^ Num2));
System.out.println("\nResult after Bitwise NOT" );
System.out.println("~Num1 = " + (~Num1));
}
void BitShift()
{
int Num1=75,Num2=-25;
System.out.println("Value of Num1 = "+Num1);
System.out.println("Binary value of Num1 = 1001011");
System.out.println("Signed Right Shift by 3 Num1/2^3= " +
(Num1>>3) );
System.out.println("Signed
Left Shift by 3 Num1*2^3= " + (Num1<<3 span="" style="mso-spacerun: yes;"> 3>
System.out.println("Value of Num2 = "+Num2);
System.out.println("Binary value of Num2 = 110010");
System.out.println("Unsigned
Right Shift by 2 = " + (Num2>>>2) );
}
}
Output
Value of Num1 and Num2 is =
25 , 5
Binary value of Num1 is
11001
Binary value of Num2 is
00101
Result after Bitwise AND
(multiplication)
Num1 & Num2 = 1
Result after Bitwise OR
(Addition)
Num1 | Num2 = 29
Result after Bitwise Ex-OR
Num1 ^ Num2 = 28
Result after Bitwise NOT
~Num1 = -26
Value of Num1 = 75
Binary value of Num1 =
1001011
Signed Right Shift by 3
Num1/2^3= 9
Signed Left Shift by 3
Num1*2^3= 600
Value of Num2 = -25
Binary value of Num2 =
110010
Unsigned Right Shift by 2 =
1073741817