Java Reference
In-Depth Information
a ˆ b
a
b
~ a
a & b
a | b
0
0
1
0
0
0
0
1
1
0
1
1
1
0
0
0
1
1
1
1
0
1
1
0
FIGURE D.3 Bitwise operations on individual bits
1 if both corresponding bits are 1. However, the exclusive OR operator ( ^ ) yields
a 0 if both operands are 1. There is no logical exclusive OR operator in Java.
When the bitwise operators are applied to integer values, the operation is per-
formed individually on each bit in the value. For example, suppose the integer
variable number is declared to be of type byte and currently holds the value 45.
Stored as an 8-bit byte, it is represented in binary as 00101101 . When the bitwise
complement operator ( ~ ) is applied to number , each bit in the value is inverted,
yielding 11010010 . Since integers are stored using two's complement representa-
tion, the value represented is now negative, specifically −46.
Similarly, for all bitwise operators, the operations are applied bit by bit,
which is where the term “bitwise” comes from. For binary operators (with two
operands), the operations are applied to corresponding bits in each operand.
For example, assume num1 and num2 are byte integers, num1 holds the value 45,
and num2 holds the value 14. Figure D.4 shows the results of several bitwise
operations.
The operators & , | , and ^ can also be applied to boolean values, and they have
basically the same meaning as their logical counterparts. When used with boolean
values, they are called boolean operators. However, unlike the operators && and
|| , which are “short-circuited,” the boolean operators are not short-circuited.
Both sides of the expression are evaluated every time.
num1 ˆ num2
num1 & num2
num1 | num2
00101101
& 00001110
00101101
| 00001110
00101101
ˆ 00001110
= 00100011
= 00001100
= 00101111
FIGURE D.4 Bitwise operations on bytes
Search WWH ::




Custom Search