Operator Name Example Defined
Bitwise complement
NOT ~x Changes 1 bits to 0 and 0 bits to 1.
& Bitwise AND x&y Bitwise AND of x and y
| Bitwise OR x|y Bitwise OR of x and y
Bitwise exclusive OR x^y Bitwise XOR of x and y
<< Left shift x<<2 Bits in x shifted left 2 bit positions
>> Right shift x>> 3 Bits in x shifted right 3 bit positions
TABLE 1. Bitwise Operators.
value the same as the original bit and
ANDing with 0 clears that bit regardless
of its state. So, you can use ANDing with
0 to ‘clear’ a bit value.
Setting and clearing bits is very
important in AVR microcontrollers since
the plethora of peripherals available are
set up by either setting or clearing the
hundreds of bits in dozens of byte-sized
registers.
bit 76543210
myByte = 11110111 = 0xF7
0x08 = 00001000 = 0x08
————————————
OR = 11111111 = 0xFF
Or maybe myByte = 0x55:
bit 76543210
myByte = 01010101 = 0x55
0x08 = 00001000 = 0x08
————————-
OR = 01011101 = 0x5D
This shows that only bit 3 of myByte is changed by
the OR operation. It is the only bit equal to 1 in 0x08, and
ORing 1 with anything else is always yields 1, so you can
use it to ‘set’ a bit regardless of that bit value.
ANDing
Setting and Clearing Bits
In each of the above cases, we are only dealing with a
single bit, but we might be interested in any or all of the
bits. Another important feature of using bitwise operators
is that it allows us to set or clear a specific bit or group of
bits in a byte without knowing the state of nor affecting
the bits we aren’t interested in. For example, suppose we
are only interested in bits 0, 2, and 6. Let’s set bit 6,
regardless of its present value, then clear bits 0 and 2, also
regardless of their present value. Here’s the trick: We must
leave bits 1, 2, 4, 5, and 7 as they were when we began.
NOTE:
myByte = myByte | 0x08;
is the same as
myByte |= 0x08;
which we will use from now on. To set bit 6, we OR
myByte with 0100000 (0x40):
Now let’s do the same thing with the & operator:
We can clear bit 3 with:
myByte = 0xAA;
myByte = myByte & 0xF7;
bit 76543210
myByte = 10101010 = 0xAA
0xF7 = 11110111 = 0xF7
————————————
AND = 10100010 = 0xA2
Or maybe myByte = 0x55:
bit 76543210
myByte = 01010101 = 0x55
0xF7 = 11110111 = 0xF7
————————————
AND = 01010101 = 0x55
From this, you see that ANDing with 1 leaves the bit
myByte = 42;
myByte |= 0x40;
bit 76543210
myByte = 00101010 = 0x2A
01000000 = 0x40
————————————
OR = 01101010 = 0x6A
Next, we want to clear bits 0 and 2 so we AND
11111010:
myByte &= 0xFA;
bit 76543210
myByte = 01101011 = 0x6B
0xFA = 11111010 = 0xFA
————————————
AND = 01101010 = 0x6A
So, in summary, we set bits with ‘|’ and clear bits
with ‘&.’
If you are going ‘Oh my God!’ at this point, I hope it
58
December 2008