posted 22 years ago
Well there are three different shift operators:
<< left shift<br /> >> signed right shift
>>> unsigned right shift
Left shifting a negative number can cause the number to change its sign depending on which bit gets shifted into the leftmost position.
int i = i << 1;<br /> 1010 0000 0000 0000 0000 0000 0000 0100 <br /> 0100 0000 0000 0000 0000 0000 0000 1000<br /> Sign changed to positive.<br /> int i = i << 2;<br /> 1010 0000 0000 0000 0000 0000 0000 0100 <br /> 1000 0000 0000 0000 0000 0000 0001 0000<br /> Sign remains negative.<br /> Signed Right Shift will always retain the same sign. Because the leftmost bit (which determines the sign) is what is shifted in. So a negative number remains negative.<br /> int i = i >> 1;<br /> 1010 0000 0000 0000 0000 0000 0000 0100<br /> 1101 0000 0000 0000 0000 0000 0000 0010<br /> Unsigned Right shift may or may not change the sign depending on the right operand of the shift operator.<br /> int i = i >>> 1;
1010 0000 0000 0000 0000 0000 0000 0100
0101 0000 0000 0000 0000 0000 0000 0010
In this case the sign is changed.
int i = i >>> 32;
1010 0000 0000 0000 0000 0000 0000 0100
1010 0000 0000 0000 0000 0000 0000 0100
In this case there is no shifting so the sign remains negative.