Page 44 - Programming Microcontrollers in C
P. 44
Operators and Expressions 29
The right shift operator and the left shift operator are also bi
nary operators. Here the types of the operands need not be the same.
The expression
x >> 3
causes the variable x to be shifted to the right by three bits prior to its
use. Likewise,
y << 5
will cause y to be shifted to the left by five bits. In all number sys
tems, a left shift by one digit corresponds to a multiplication by the
number base. Similarly, a shift to the right by one digit causes a
division by the number base. We are using the binary system in this
case, so a shift left by one bit causes the number to be multiplied by
two. Unlike most number systems, the binary system (or two’s
complement system) allows the sign of the number to be contained
in the binary representation of the number itself. These consider
ations lead to two different types of shifts for a system of binary
numbers. A shift in which bits vacated by the shift are replaced by
zeros is called a logical shift. All left shifts are logical shifts. As the
shift progresses toward the left, bits that fill the number from the
right will all be zero. Bits that shift out of the number on the left side
are lost. A right shift can be either a logical or an arithmetic shift. If
the type being shifted is signed, the sign bit—which is the leftmost
bit—will propagate, retaining a number of the same sign. This is an
arithmetic sign. If the number being shifted is unsigned, zeros are
filled into the number from the left as the shift proceeds. In all cases,
bits shifted out of a number by a shift operation will be lost. The
one’s complement operator ~ is a unary operator that causes the bits
in a variable to be reversed. Every 1 is replaced by a 0, and every 0 is
replaced by a 1. The bitwise AND and OR operations are used to turn
bits on and off. Suppose that we have a character variable r, and we
wish to turn the least significant three bits off. Try
r = r & ~7;
In this case, the number 7 has each of the least significant bits turned
on or 1. Therefore, the term ~7 has all of the bits in the number but
the least significant turned on and these three bits are turned off or 0.