Java Reference
In-Depth Information
either
bit is 1, and the
XOR
of two bits yields a 1 only if the two bits have
different
values. For example:
0xf00f & 0x0ff0 yields 0x0000
0xf00f | 0x0ff0 yields 0xffff
0xaaaa ^ 0xffff yields 0x5555
There is also a unary bitwise complement operator
~
, which toggles each
bit in its operand. An
int
with value
0x00003333
has a complemented
value of
0xffffcccc
.
Although the same characters are used for the bitwise operators and the
logical operators, they are quite distinct. The types of the operands de-
termine whether, for example,
&
is a logical or a bitwise
AND
. Since logic-
al operators only apply to booleans and bitwise operators only apply to
integer types, any expression involving operands of the different types,
such as
TRue& 0xaaaa
, is a compile-time error.
There are other bit manipulation operators to shift bits within an integer
value:
<<
Shift bits left, filling with zero bits on the right-hand side
Shift bits right, filling with the highest (sign) bit on the left-hand
side
>>
>>>
Shift bits right, filling with zero bits on the left-hand side
The left-hand side of a shift expression is what is shifted, and the right-
hand side is how much to shift. For example,
var>>> 2
will shift the bits