In Java there are different bitwise operatora. These can be applied to long, int, short, char and byte. These operators acts on the singles bits ov a value.
Rappresentation of the integers
All the integers are rappresented by binary numbers where every position is a power of 2.From right to leftwe have 2^{0},2^{1},2^{2},2^{3}……2^{n}.
For Example Take the binary version of 40, 101000, as you can see there are only two 1, the first in position 6, that is 2^{5 }that is 32, the other 1 is in position 3 that is 8. So 32 + 8 = 40.
Exept for the char , all the integer types are both positive and negative, there is not such an unsigned type. to obtainthe negative number in binary from a positive, you just need to invert all the bits and add 1 at the result. Take the previous example, 00101000 is +40, to obtain its negative value, invert all the bits, 11010111 and add a 1, 11011000. To obtan now again the positive, use the same method, change all the bits like this 00100111, and add 1 00101000.
A | B | A| B | A & B | A ^ B | ~ |
0 | 0 | 0 | 0 | 0 | 1 |
1 | 0 | 1 | 0 | 1 | 0 |
0 | 1 | 1 | 0 | 1 | 1 |
1 | 1 | 1 | 1 | 0 | 0 |
NOT operator ~ invert all bits of the operand. 00101000 -> 11010111.
AND operator & give 1 if both the operands are 1, 0 in the other cases.
OR operator | give 1 if both the operands are 0, 0 in the other cases.
XOR operator ^ give 1 if one of the operands is 1, 0 in the other cases.
Bitwise Shifts Operators
The << operator (left shift), shift all the bits in a value to the left, a certain amount of times. The leftmost bit is shifted out. In an int is shifted out once pasted the position 31, in a long, after position 63. Another story is for short and byte. These are automatically promoted to int during the shifting. So to obtain short and byte you must cast the result of the shifted value.
The >> operator (right shift), shift all the bits to the right a specified number of times. Bits are lost when they shift off. The leftmost bits are filled with the previous content of the leftmost bit.
The >>> operator ( unsigned right shift) works like the previous exept that it will fill the leftmost bits with zeros, regardless the sign and so the previous content.
Every binary bitwise operator can be combined with the assignement operator like this: x = x >> 5 can be written like this, x >>= 5;