Bitwise Operators
There are six bitwise operators, described in Table 1-13. All of them require integer operands.
Operator |
Meaning |
Example |
Result (for each bit position) |
& |
bitwise |
x & y |
|
| |
bitwise |
x | y |
|
^ |
bitwise exclusive |
x ^ y |
|
~ |
bitwise |
~x |
|
<< |
shift left |
x << y |
Each bit in |
>> |
shift right |
x >> y |
Each bit in x is shifted y positions to the right |
The logical bitwise operators,
&
(AND), |
(OR),
^
(exclusive OR), and ~
(NOT)
interpret their operands bit by bit: a bit that is set, i. e.,
1
, is considered
“true”; a cleared bit, or
0
, is “false”.
Thus, in the result of z = x & y
, each bit is
set if and only if the corresponding bit is set in both
x
and y
. The usual arithmetic
conversions are performed on the operands.
The shift operators <<
and
>>
transpose the bit pattern of the left
operand by the number of bit positions indicated by the right
operand. Integer promotions are performed beforehand on both
operands. The result has the type of the left operand after integer
promotion. Some examples are:
int x = 0xF, result; result = x << 4; // yields 0xF0 result = x >> 2; // yields 0x3
The bit positions vacated at the right by the left shift
<<
are always filled with
0
bits. Bit values shifted out to the left are
lost.
The bit positions vacated at the ...
Get C Pocket Reference now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.