Using the bitwise shift operators
#include <iostream>
#include <iomanip>
using namespace std;
void displayBits( unsigned );
int main()
{
unsigned number1 = 960;
cout << "The result of left shifting\n";
displayBits( number1 );
cout << "8 bit positions using the left "
<< "shift operator is\n";
displayBits( number1 << 8 );
cout << "\nThe result of right shifting\n";
displayBits( number1 );
cout << "8 bit positions using the right "
<< "shift operator is\n";
displayBits( number1 >> 8 );
return 0;
}
void displayBits( unsigned value )
{
unsigned c, displayMask = 1 << 15;
cout << setw( 7 ) << value << " = ";
for ( c = 1; c <= 16; c++ ) {
cout << ( value & displayMask ? '1' : '0' );
value <<= 1;
if ( c % 8 == 0 )
cout << ' ';
}
}
Related examples in the same category