Bitwise operators are related to the logical operators in that they perform logical
operations (AND, OR, NOT, XOR), but they perform them on every individual bit in
an integer. As
shows, they also include additional shift operators to shift bits
into different positions.
Table 5-7. Bitwise operators
Operator
Description
Example
&
Bitwise AND
0b1010 & 0b1100 // result: 0b1000
|
Bitwise OR
0b1010 | 0b1100 // result: 0b1110
^
Bitwise XOR
0b1010 ^ 0b1100 // result: 0b0110
~
Bitwise NOT
~0b1010 // result: 0b0101
<<
Left shift
0b1010 << 1 // result: 0b10100
0b1010 << 2 // result: 0b101000
>>
Sign-propagating right shift (See below)
>>>
Zero-fill right shift
(See below)
Note that left shifting is effectively multiplying by two, and right shifting is effectively
dividing by two and rounding down.
In two’s complement, the leftmost bit is 1 for negative numbers, and 0 for positive
numbers, hence the two ways to perform a right shift. Let’s take the number –22, for
example. If we want to get its binary representation, we start with positive 22, take the
complement (one’s complement), and then add one (two’s complement):
let
n
=
22
// 32-bit binary: 00000000000000000000000000010110
n
>>
1
// 00000000000000000000000000001011
n
>>>
1
// 00000000000000000000000000001011
n
=
~
n
// one's complement: 11111111111111111111111111101001
n
++
// two's complement: 11111111111111111111111111101010
n
>>
1
// 11111111111111111111111111110101
n
>>>
1
// 01111111111111111111111111110101
Unless you are interfacing with hardware, or getting a better grasp on how numbers
are represented by a computer, you’ll probably have little call to use bitwise operators
(often playfully called “bit twiddling”). One nonhardware use you may see is using
bits to efficiently store “flags” (boolean values).
94 | Chapter 5: Expressions and Operators