One power of C/C++ is the ability to perform low-level operations that are done by machine languages. These operations are performed on bits. Recall, numbers and addresses are represented in binary form internally. In many applications, especially hardware, it is desirable to work with these bits. The language of C/C++ is known as a language that works closely with hardware. Because of the importance of bit-wise operations, C/C++ chooses to use one key strike for bit-wise operators (&, |) and two strikes for the logical operators (&&, ||). The following symbols are used for the C/C++ bit-wise operations.
| bit-wise or operator
& bit-wise and operator
^ bit-wise exclusive or operator
<< shift left operator
>> shift right operator
~
bit complement (unary operator)
The general form of the bit-wise
or
operation is variable1 |
variable2 where each variable of
type integer is converted to binary (bits). The bit-wise or
operation of two bits is zero if both corresponding bits are zero (0),
otherwise the resulting bit is one (1).
The general form of the bit-wise and (&)
is variable1
& variable2, where each variable of type integer is converted to
binary. The bit-wise and
operation of two bits is one if the two corresponding bits have
values of 1, otherwise the resulting bit is zero.
The general form of the bit-wise
exclusive
or (^) operation is variable1
^ variable2, where both variables and resulting variable are of type
integer and are converted to binary.