|
| 1 | +package BitwiseOperators; |
| 2 | + |
| 3 | +public class Operators { |
| 4 | + /** |
| 5 | + * Operators that work directly on BINARY representations of numbers. |
| 6 | + * • AND - & (return true only when both of the symbols are 1. |
| 7 | + * [ 0,0 :- 0; 0,1 :- 0 ; 1,0 :- 0; 1,1 :- 1]) |
| 8 | + * • OR - | (return true even if one of the symbol is 1. |
| 9 | + * [1,0 :- 1; 0,1 :- 1 ; 1,0 :- 1; 0,0 :- 0]) |
| 10 | + * • XOR - ^ (return true only when one of the symbol is different. |
| 11 | + * [0,0 :- 0; 0,1 :- 1 ; 1,0 :- 1; 1,1 :- 0]) |
| 12 | + * • Not - ~ (return true when both the bits are equal. |
| 13 | + * [0,0 :- 1; 0,1 :- 0 ; 1,0 :- 0; 1,1 :- 1]) |
| 14 | + * • LeftShift - << (Shifts the bits of a number to the left by a specified number of positions.) |
| 15 | + * • RightShift - >> (Shifts the bits of a number to the right by a specified number of positions.) |
| 16 | + */ |
| 17 | + public static void main(String[] args) { |
| 18 | + System.out.println("5 & 3: " + (5 & 3)); |
| 19 | + /* 1 0 1 -> 5 |
| 20 | + 0 1 1 -> 3 |
| 21 | + ----------- |
| 22 | + 0 0 1 -> 1 (output) |
| 23 | + */ |
| 24 | + System.out.println("5 | 3: " + (5 | 3)); |
| 25 | + /* 1 0 1 -> 5 |
| 26 | + 0 1 1 -> 3 |
| 27 | + ----------- |
| 28 | + 1 1 1 -> 7 (output) |
| 29 | + */ |
| 30 | + System.out.println("5 ^ 3: " + (5 ^ 3)); |
| 31 | + /* 1 0 1 -> 5 |
| 32 | + 0 1 1 -> 3 |
| 33 | + ----------- |
| 34 | + 1 1 0 -> 6 (output) |
| 35 | + */ |
| 36 | + System.out.println("10 << 2 :" + (10 << 2)); //(input << positions) shift the bits to left and add 2 bits to the right |
| 37 | + /* |
| 38 | + 1 0 1 0 -> 10 (input) |
| 39 | + _ _ _ _ _ _ |
| 40 | + 1 0 1 0 0 0 -> 40 (output) */ |
| 41 | + |
| 42 | + System.out.println("10 >> 2 :" + (10 >> 2)); //(input >> positions) shift the bits to right means simply remove 2 bits from right. |
| 43 | + /* |
| 44 | + 1 0 1 0 -> 10 (input) |
| 45 | + _ _ _ _ |
| 46 | + 1 0 -> 2 (output) |
| 47 | + dropped bits - 1 0 */ |
| 48 | + |
| 49 | + } |
| 50 | +} |
0 commit comments