Sams Teach Yourself C in 21 Days

(singke) #1
Working with Memory 583

20


Binary 00001100 (decimal 12 ) right-shifted by 2 evaluates to binary 00000011 (deci-
mal 3 ).
Binary 00001100 (decimal 12 ) left-shifted by 3 evaluates to binary 01100000 (decimal
96 ).
Binary 00001100 (decimal 12 ) right-shifted by 3 evaluates to binary 00000001 (deci-
mal 1 ).
Binary 00110000 (decimal 48 ) left-shifted by 3 evaluates to binary 10000000 (decimal
128 ).

Under certain circumstances, the shift operators can be used to multiply and divide an
integer variable by a power of 2. Left-shifting an integer by nplaces has the same effect
as multiplying it by 2n, and right-shifting an integer has the same effect as dividing it by
2 n. The results of a left-shift multiplication are accurate only if there is no overflow—that
is, if no bits are “lost” by being shifted out of the high-order positions. A right-shift divi-
sion is an integer division, in which any fractional part of the result is lost. For example,
if you right-shift the value 5 (binary 00000101 ) by one place, intending to divide by 2,
the result is 2 (binary 00000010 ) instead of the correct 2.5, because the fractional part
(the.5) is lost. Listing 20.7 demonstrates the shift operators.

LISTING20.7 shiftit.c. Using the shift operators
1: /* Demonstrating the shift operators. */
2:
3: #include <stdio.h>
4:
5: int main( void )
6: {
7: unsigned int y, x = 255;
8: int count;
9:
10: printf(“Decimal\t\tshift left by\tresult\n”);
11:
12: for (count = 1; count < 8; count++)
13: {
14: y = x << count;
15: printf(“%d\t\t%d\t\t%d\n”, x, count, y);
16: }
17: printf(“\n\nDecimal\t\tshift right by\tresult\n”);
18:
19: for (count = 1; count < 8; count++)
20: {
21: y = x >> count;
22: printf(“%d\t\t%d\t\t%d\n”, x, count, y);
23: }
24: return 0;
25: }

INPUT

32 448201x-CH20 8/13/02 11:16 AM Page 583

Free download pdf