The shift operators shift the bits in the left operand by the number of positions specified by the right operand.
You could specify a shift-left operation with the following statements:
int value = 12; int shiftcount = 3; // Number of positions to be shifted int result = value << shiftcount; // Shift left shiftcount positions
The variable result will contain the value 96.
The binary number in value is 0000 1100.
The bits are shifted to the left three positions.
0s are introduced on the right, so the value of value << shiftcount, as a binary number, will be 0110 0000.
The right shift operator moves the bits to the right.
For unsigned values, the bits that are introduced on the left are filled with zeros.
Suppose you declare a variable:
unsigned int value = 65372U;
As a binary value in a two-byte variable, this is 1111 1111 0101 1100.
Suppose you now execute the following statement:
unsigned int result = value >> 2; // Shift right two bits The bits in value will be shifted two places to the right, introducing zeros at the left end.
In binary this will be 0011 1111 1101 0111, which is the decimal value 16343.
1111 1111 0101 1100 0011 1111 1101 0111
For signed values that are negative, the leftmost bit will be 1.
The sign bit is propagated, so the bits introduced on the right are 1 bits.
Suppose you define a variable with this statement:
int new_value = -164;
In binary new_value is 1111 1111 0101 1100;
Suppose you now execute this statement:
int new_result = new_value >> 2; // Shift right two bits
This will shift the value in new_value two bit positions to the right.
As usual case, the sign bit is propagated, 1's will be inserted on the left as the bits are shifted to the right, so new_result will end up as 1111 1111 1101 0111.
This is the decimal value -41.