Win a copy of Penetration Testing Basics this week in the Security forum!

# Question on shift operator

Anjana Ravindran
Ranch Hand
Posts: 76
What is the output of the following code block?
public class test {
public static void main(String args[]) {
int i = -1;
i = i >> 1;
System.out.println(i);
}
}

i believe it is 0. it is a question from a site. it says the answer as -1. i doubt it. wat u say?

Sachin Dimble
Ranch Hand
Posts: 100
in java negative no represents with 2's complment form which means-

int -1-> java representation 0 001->1's compliment 1 110->2's compliment 1111 now this no will get rightshifted->0111->to get back apply rverse process i.e->1's compliment 1 000->2's compliment 1 001

in this no high order bit is 1 hence no will negative & no is 001 i.e->-1.

Hope will understand this!!

Sachin Dimble.

Enge Chall
Ranch Hand
Posts: 30
check for 2's complemen calculation link :

There is a little trick to calculate faster in the exam for -ve numbers:
If it's a odd number let's say (2n + 1) format, then add 1 and devide by 2.. ie your answer in -ve.

ie to get -15 >> 1, answer is -(15+1)/2 = -8
Similarly -16 >> 1, answer is 16/2=8.

Guys, thank me for saving ur binary calculation time
[ December 08, 2005: Message edited by: Enge Chall ]

Naresh Gunda
Ranch Hand
Posts: 163
>>

As the bits are shifted right, the sign bit(left most) is used to fill in from the left. So if the left hand operand is a positive value, zeros are filled in from the left, but if the operand is a negative value, ones are filled in from the left.

public class Test {
public static void main(String args[]) {
int i = -1;
System.out.println( Integer.toBinaryString(i));
System.out.println( Integer.toBinaryString(i>>1));
i = i >> 1;
System.out.println(i);
}
}

Hope this helps u
Regards
Naresh