Chapter 4: C Types, Operators, and Expressions
Bitwise Operators
Table 5: Bitwise Operators
Operator Name Example Defined
~ Bitwise complement ~x Changes 1 bits to 0 and 0 bits to 1
NOT
& 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
Bitwise operators are critically important in microcontroller software. They allow
s to do many things in C that can be directly and efficiently translated into
microcontroller machine operations. Keep in mind that these operators work on
bits but are similar enough to the logical operators that you will get confused.
Let’s look at the truth tables for &, |, and ^:
AND OR XOR
0 & 0 = 0 0 | 0 = 0 0 ^ 0 = 0
0 & 1 = 0 0 | 1 = 1 0 ^ 1 = 1
ns on it:
e can starting with 0):
s happening Let’s look at these in binary:
myByte =
u
1 & 0 = 0 1 | 0 = 1 1 ^ 0 = 1
1 & 1 = 1 1 | 1 = 1 1 ^ 1 = 0
Let’s create a variable, myByte and do some bitwise operatio
unsigned char myByte = 0;
W set bit 3 (numbering from the right
myByte = myByte | 0x08;
To see what’
00000000 = 0x00