Shift Operators

The two shift operators (considered to be bitwise operators):

symbol meaning
<< shift left
>> shift right

can only be applied to integer types. An expression of the form:

	a<<b

means: 'a' shifted to the left 'b' bit positions. While the other:

	a>>b

would mean 'a' shifted to the right 'b' bit positions. If the left hand operand is unsigned, then zeros are shifted in and the bits that are shifted out are discarded.

For each shift left by one position the left hand operand is doubled. While for each shift right by one position the left hand operand is halved.

If the left hand operand is signed then what is called an arithmetic shift is performed. In an arithmetic shift, the sign bit does not move.

In an arithmetic shift left, the bits to the right of the sign bit shift left and fall off without affecting the sign bit while zero bits shift in from the right (or least significant bit).

In an arithmetic shift right, instead of shifting in zeros, the sign bit which still remains fixed) is propagated to the right and repeated as many times as the shift count (right hand operand).

Arithmetic shifts also double or halve the left hand operand except for one special case. Minus one shifted right is still minus one!

The shift operation are only defined for positive shift counts (right hand operands). The result for negative shift counts is implementation dependent. Even though a given implementation will always do the same thing, it may be different with another machine or compiler.


© 1991-2008 Prem Sobel. All Rights Reserved.