Java Reference
In-Depth Information
Bitwise Operators
A bitwise operator manipulates individual bits of its operands. Bitwise operators are listed in Table 4-7 .
Table 4-7. List of Bitwise Operators
Operators
Meaning
Type
Usage
Result
&
25 & 24
24
Bitwise AND
Binary
|
25 | 2
27
Bitwise OR
Binary
^
25 ^ 2
27
Bitwise XOR
Binary
~
~25
-26
Bitwise complement (1's complement)
Unary
<<
25 << 2
100
Left shift
Binary
>>
25 >> 2
6
Signed right shift
Binary
>>>
25 >>> 2
6
Unsigned right shift
Binary
&= , != , ^= , <<= , >>= , >>>=
Compound assignment Bitwise operators
Binary
All bitwise operators work with only integers. The bitwise AND (&) operator operates on corresponding bits of its
two operands and returns 1 if both bits are 1, and 0 otherwise. Note that the bitwise AND (&) operates on each bit of
the respective operands, not on the operands as a whole. The following is the result of all bit combination using the
bitwise AND ( & ) operator:
1 & 1 = 1
1 & 0 = 0
0 & 1 = 0
0 & 0 = 0
Consider the following piece of code in Java:
int i = 13 & 3;
The value of 13 & 3 is computed as follows. The 32 bits have been shown in 8-bit chunks for clarity. In memory,
all 32 bits are contiguous.
13 00000000 00000000 00000000 00001101
3 00000000 00000000 00000000 00000011
----------------------------------------------
13 & 3 - 00000000 00000000 00000000 00000001 (Equal to decimal 1)
Therefore, 13 & 3 is 1, which is assigned to i in the above piece of code.
The bitwise OR ( | ) operates on corresponding bits of its operands and returns 1 if either bit is 1, and 0 otherwise.
The following is the result of all bit combinations using bitwise OR ( | ) operator:
1 | 1 = 1
1 | 0 = 1
0 | 1 = 1
0 | 0 = 0
 
 
Search WWH ::




Custom Search