## Sunday, August 14, 2011

### Shift Operators

Left-shift <<

bits are shifted to the left based on the value of the right-operand
new right hand bits are zero filled
equivalent to left-operand times two to the power of the right-operand

For example, 16 << 5 = 16 * 2^5 = 512 Decimal 16 00000000000000000000000000010000 Left-shift 5 00000000000000000000000000010000 fill right 0000000000000000000000000001000000000 discard left 00000000000000000000001000000000 the sign-bit is shifted to the left as well, so it can be dropped off or a different sign can replace it Right-shift >>

bits are shifted to the right based on value of right-operand
new left hand bits are filled with the value of the left-operand high-order bit therefore the sign of the left-hand operator is always retained
for non-negative integers, a right-shift is equivalent to dividing the left-hand operator by two to the power of the right-hand operator

For example: 16 >> 2 = 16 / 22 = 4

Decimal 16 00000000000000000000000000010000

Right-shift 2 00000000000000000000000000010000
fill left 00000000000000000000000000000100
discard right 00000000000000000000000000000100 -&gt; Decimal 4

Decimal -16 11111111111111111111111111110000

Right-shift 2 11111111111111111111111111110000
fill left 1111111111111111111111111111110000
discard right 11111111111111111111111111111100 -&gt; Decimal -4

Unsigned right-shift >>>

identical to the right-shift operator only the left-bits are zero filled
because the left-operand high-order bit is not retained, the sign value can change

if the left-hand operand is positive, the result is the same as a right-shift
if the left-hand operand is negative, the result is equivalent to the left-hand operand right-shifted by the number indicated by the right-hand operand plus two left-shifted by the inverted value of the right-hand operand

For example: -16 >>> 2 = (-16 >> 2 ) + ( 2 << ~2 ) = 1,073,741,820 Decimal 16 00000000000000000000000000010000 Right-shift 2 00000000000000000000000000010000 fill left 00000000000000000000000000000100 discard right 00000000000000000000000000000100 > Decimal 4

Decimal -16 11111111111111111111111111110000

>>> 2 11111111111111111111111111110000
fill left 0011111111111111111111111111110000