Java supports several bitwise operators, which can be applied to the integer types, long, int, short, char, and byte. These Bitwise operator works on bits and performs the bit-by-bit operation.
For Example: Assume if a = 60 and b = 13; now in the binary format they will define follows:
a = 0011 1100
b = 0000 1101
-----------------
a&b = 0000 1100
a|b = 0011 1101
a^b = 0011 0001
~a = 1100 0011
See Also :
Here is a complete list of bitwise operators:
Operator | Result |
~ | Bitwise unary NOT |
& | Bitwise AND |
| | Bitwise OR |
^ | Bitwise exclusive OR |
>> | Shift right |
>>> | Shift right zero fill |
<< | Shift left |
&= | Bitwise AND assignment |
|= | Bitwise OR assignment |
^= | Bitwise exclusive OR assignment |
>> | Shift right assignment |
>>>= | Shift right zero-fill assignment |
<<= | Shift left assignment |
Bitwise Logical Operators:
Here is a table of the result after performing a bitwise operator on values A and B.
A | B | A | B | A & B | A ^ B | ~A |
0 | 0 | 0 | 0 | 0 | 1 |
1 | 0 | 1 | 0 | 1 | 0 |
0 | 1 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 | 0 |
Bitwise Operator Example
public class BitwiseOperatorTest { public static void main(String[] args) { //Bitwise And System.out.println(9 & 7); //Bitwise or System.out.println(19 | 7); //Bitwise XOR System.out.println(9 ^ 7); //left Shift System.out.println(9 << 7); //Bitwise complement(~), Inverts ones and zeros in a number int i = 1; System.out.println(i); int j = ~i + 1; System.out.println(j); i = ~j + 1; System.out.println(i); //Example Bitwise demonstration String binary[] = { "0000", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010", "1011", "1100", "1101", "1110", "1111" }; int a = 3; // 0 + 2 + 1 or 0011 in binary int b = 6; // 4 + 2 + 0 or 0110 in binary int c = a | b; int d = a & b; int e = a ^ b; int f = (~a & b) | (a & ~b); int g = ~a & 0x0f; System.out.println(" a = " + binary[a]); System.out.println(" b = " + binary[b]); System.out.println(" a|b = " + binary); System.out.println(" a&b = " + binary[d]); System.out.println(" a^b = " + binary[e]); System.out.println("~a&b|a&~b = " + binary[f]); System.out.println(" ~a = " + binary[g]); } }
Output
1
23
14
1152
1
-1
1
a = 0011
b = 0110
a|b = 0111
a&b = 0010
a^b = 0101
~a&b|a&~b = 0101
~a = 1100
You must log in to post a comment.