Figure 20.11 demonstrates the left-shift operator (<<) and the right-shift operator (>>). Function displayBits
(lines 27–45) prints the unsigned
integer values.
1 // Fig. 20.11: fig20_11.cpp
2 // Using the bitwise shift operators.
3 #include <iostream>
4 #include <iomanip>
5 using namespace std;
6
7 void displayBits( unsigned ); // prototype
8
9 int main()
10 {
11 unsigned number1 = 960;
12
13 // demonstrate bitwise left shift
14 cout << "The result of left shifting
";
15 displayBits( number1 );
16 cout << "8 bit positions using the left-shift operator is
";
17 displayBits( number1 << 8
);
18
19 // demonstrate bitwise right shift
20 cout << "
The result of right shifting
";
21 displayBits( number1 );
22 cout << "8 bit positions using the right-shift operator is
";
23 displayBits( number1 >> 8
);
24 } // end main
25
26 // display bits of an unsigned integer value
27 void displayBits( unsigned value )
28 {
29 const int SHIFT = 8 * sizeof( unsigned ) - 1;
30 const unsigned MASK = 1 << SHIFT;
31
32 cout << setw( 10 ) << value << " = ";
33
34 // display bits
35 for ( unsigned i = 1; i <= SHIFT + 1; ++i )
36 {
37 cout << ( value & MASK ? '1' : '0' );
38 value <<= 1; // shift value left by 1
39
40 if ( i % 8 == 0 ) // output a space after 8 bits
41 cout << ' ';
42 } // end for
43
44 cout << endl;
45 } // end function displayBits
The result of left shifting
960 = 00000000 00000000 00000011 11000000
8 bit positions using the left-shift operator is
245760 = 00000000 00000011 11000000 00000000
The result of right shifting
960 = 00000000 00000000 00000011 11000000
8 bit positions using the right-shift operator is
3 = 00000000 00000000 00000000 00000011
3.134.103.74