C Tutorial/Operator/Shift operator
Using the bitwise shift operators
<source lang="cpp">#include <stdio.h> void displayBits( unsigned value ); int main() {
unsigned number1 = 960; printf( "\nThe result of left shifting\n" ); displayBits( number1 ); printf( "8 bit positions using the " ); printf( "left shift operator << is\n" ); displayBits( number1 << 8 ); printf( "\nThe result of right shifting\n" ); displayBits( number1 ); printf( "8 bit positions using the " ); printf( "right shift operator >> is\n" ); displayBits( number1 >> 8 ); return 0;
} void displayBits( unsigned value ) {
unsigned c; unsigned displayMask = 1 << 31; printf( "%7u = ", value ); for ( c = 1; c <= 32; c++ ) { putchar( value & displayMask ? "1" : "0" ); value <<= 1; if ( c % 8 == 0 ) { putchar( " " ); } } putchar( "\n" );
}</source>
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