Bit Operations
In embedded computing, you often have to manipulate bits. You sometimes
have to read single bits to get some sensor data. In other cases, you have to
set bits to turn a device into a certain status or to make it perform some
action.
For bit manipulation, you need only a few operations. The simplest is the not
operation that inverts a bit. It turns a 0 into a 1 and vice versa. Most program-
ming languages implement the binary not operation with a ~ operator:
int x = 42; // In binary this is 101010
int y = ~x; // y == 010101
In addition, you’ll find three binary operations named AND, OR, and XOR
(eXclusive OR). Most programming languages call the corresponding operators
&, |, and ^, and their definitions are as follows:
a XOR b
a ^ b
a OR b
a | b
a AND b
a & b
ba
00000
11001
11010
01111
With these operators, it’s possible to mask bits in a number, so you can
extract certain bits. If you’re interested only in the lower two bits of a number,
you can do it as follows:
int x = 42; // In binary this is 101010
int y = x & 0x03; // y == 2 == B10
You can also set one or more bits in a number using the OR operation. The
following code sets the fifth bit in
x
regardless of whether this bit is 0 or 1.
int x = 42; // In binary this is 101010
int y = x | 0x10; // y == 58 == B111010
The bit shift operators « and » let you move bits to a certain position before
you work with them. The first one moves bits to the left, and the second moves
them to the right:
int x = 42; // In binary this is 101010
int y = x << 1; // y == 84 == B1010100
int z = x >> 2; // z == 10 == B1010
report erratum • discuss
Bit Operations • 251
www.it-ebooks.info