Page 45 - Programming Microcontrollers in C
P. 45
30 Chapter 1 Introduction to C
When this mask is ANDed with r, all of the bits of r, with the
exception of the least significant three bits, will be ANDed with a 1,
and these bit values will remain unchanged. The least significant
three bits will be ANDed with 0 and the result in these three bits will
be 0. The bitwise OR will turn bits on. Suppose you wanted to turn
bits 2 and 3 of r above on. Here you would use
r = r | 0x0c;
The hexadecimal number 0x0c is a number that has bits 2 and 3
turned on and all other bits turned off. This OR operation will leave
bits 2 and 3 on and all other bits will remain unchanged. Suppose
that you want to complement a bit in a variable. For example, bit 0 of
the memory location PORTA must be toggled each time a certain
routine is entered. The expression
PORTA = PORTA ^ 1;
will perform this operation. All of the bits except for bit 1 of PORTA
will remain unchanged because the exclusive OR of any bit with a 0
will not change the bit value. However, if bit 1 is 1 in PORTA the
exclusive OR will force this bit to 0. If this bit is 0, the exclusive OR
will force this bit to a 1. Therefore, the above expression will comple
ment bit 0 of PORTA each time it is executed.
The bitwise operators &, |, and ^ are of lower precedence
than the equality operators, and higher precedence than the logical
AND operator. The bit shift operators are of the same precedence, of
lower precedence than the arithmetic operators + and - , and of higher
precedence than the relational operators.
Increment and Decrement Operators
When the C language was written, every effort was made to write
a language that is concise and yet unambiguous. Several powerful
short-hand operators were included in the language that will shorten
the program. The increment and decrement operators are examples
of such short-hand operators. In the examples earlier there were in
stances of expressions such as
i = i + 1;