Bitwise operators

C also provides a set of operators which manipulate unsigned integer types as patterns of bits. These should be carefully distinguished from the Boolean operators, which deal with logical values of zero and non-zero (false and true). Bitwise operators work with all the bits in a pattern.
~bitwise complement (one's complement)inverts all bits
<<left shift move to the left the bits in the first operand, with zeros carried in on the right, by the number of places given by the second operand
>>right shift move to the right the bits in the first operand, with zeros carried in on the left, by the number of places given by the second operand
&bitwise ANDANDs each bit in the first operand with the corresponding bit in the second operand
|bitwise ORORs each bit in the first operand with the corresponding bit in the second operand
^bitwise exclusive ORXORs each bit in the first operand with the corresponding bit in the second operand


Truth table for XOR
xyx ^ y
ttf
tft
ftt
fff


Examples

4 << 2 = 16
4 >> 1 = 2
7 & 3 = 3
9 | 6 = 15
9 | 7 = 15
9 ^ 6 = 15
9 ^ 7 = 14

Some uses

and
used to mask bits, i.e. to select certain bits from a pattern. If the result is non-zero, at least one of the mask bits is set in the pattern. Used to test bits set as flags and the set operations intersection and membership test on sets implemented as bit patterns.
or
used to set bits in a status field, as flags which can be tested later with and. Also can be used as a set union operation between sets implemented as bit patterns.
XOR
commonly used to implement overlaying of images, such as a cursor onto a computer screen. After XOR operation, cursor will show as black where image is white and as white where screen is black.

Exercises on this section.


Next - Operator precedence

Back to expressions.

Back to Contents page.