Reputation: 837
public class Shift{
public static void shift1(){
int i = 0;
while(-1 << i != 0){
i++
}
}
public void shift2(){
for(int i=-1;i!=0;i<<=1){
System.out.println(i);
}
}
}
The first method goes to infinite loop where as second iterates 31 times to become 0;why does java only consider the lower order 5 bits of right operand while shifting?
Upvotes: 2
Views: 97
Reputation: 424983
The "lowest 5 bits" is not relevant.
-1 is represented as 32 "1" bits: 11111111111111111111111111111111
Each << 1
operation chews up one of those bits until i
is zero - that's what's controlling the number of iterations.
Upvotes: 0
Reputation: 4733
Shifting by 32 or more isn't done by Java both because it's a fairly useless operation on ints, and simply because that is how it is specified to work.
Upvotes: 2
Reputation: 310859
Because that's what is specified in the Java Language Specification: "If the promoted type of the left-hand operand is int, only the five lowest-order bits of the right-hand operand are used as the shift distance."
A lot of hardware works that way as well.
Upvotes: 5