I have this demo program which shows the concept of shift operator in java.But i’m not clear how this program generates this answer.So please suggest me how to do this.
public class Operator {
public static void main(String[] args) {
int s = -10;
s = s >>2;
System.out.println("value of i=" + s);
}
}
Output:
value of i=-3
111101102 >> 2 == 111111012 == -310
That’s a sign-extended shift-right operation — as it shifts right, it doesn’t insert zeros at left, but copies the value of the highest bit. The rest of the explanation is about two’s complement representation of signed integers.
In general, right-shifting a negative integer by
npositions will have the effect of dividing by 2n and subtracting 1 from that.