Java Reference
In-Depth Information
A
PPENDIX
G
Bitwise Operations
To write programs at the machine-level, often you need to deal with binary numbers directly
and perform operations at the bit-level. Java provides the bitwise operators and shift operators
defined in Table G.1.
The bit operators apply only to integer types (
byte
,
short
,
int
, and
long
). A character
involved in a bit operation is converted to an integer. All bitwise operators can form bitwise
assignment operators, such as
=
,
|=
,
<<=
,
>>=
, and
>>>=
.
T
ABLE
G.1
Example
(using bytes in the example)
Operator
Name
Description
&
Bitwise AND
10101110
&
10010010
yields 10000010
The AND of two corresponding
bits yields a 1 if both bits are 1.
|
Bitwise
inclusive OR
10101110
|
10010010
yields 10111110
The OR of two corresponding bits
yields a 1 if either bit is 1.
^
Bitwise
exclusive OR
10101110
^
10010010
yields 00111100
The XOR of two corresponding
bits yields a 1 only if two bits are
different.
~
One's
complement
~
10101110 yields
01010001
The operator toggles each bit from
0 to 1 and from 1 to 0.
Left shift
10101110
<<
2 yields
10111000
The operator shifts bits in the first
operand left by the number of bits
specified in the second operand,
filling with 0s on the right.
<<
>>
Right shift
with sign
extension
10101110
>>
2 yields
11101011
00101110
>>
2 yields
00001011
The operator shifts bit in the first
operand right by the number of bits
specified in the second operand,
filling with the highest (sign) bit
on the left.
>>>
Unsigned right
shift with zero
extension
10101110
>>>
2 yields
00101011
00101110
>>>
2 yields
00001011
The operator shifts bit in the first
operand right by the number of bits
specified in the second operand,
filling with 0s on the left.
1277
Search WWH ::
Custom Search