Win a copy of Kotlin in Action this week in the Kotlin forum!
programming forums Java Java JSRs Mobile Certification Databases Caching Books Engineering Languages Frameworks Products This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
Sheriffs:
Saloon Keepers:
Bartenders:

# Question on Shift - left Operator .

Joe Man
Ranch Hand
Posts: 71
Hello All,
This is my first time posting a message.
Can someone explain to me why the answer is 56?
public class Empty{
public static void main(String args[]){
System.out.println(7 << 32003);
}
}

Rob Ross
Bartender
Posts: 2205
Do a search on shift operators in this forum and you will find many many threads about this topic.
The short answer is that when the left-hand operand is an int type, only the 5 least-significant bits of the right-hand side operand are used. If the left-hand side operand is a long type, then the least-significant 6 bits of the right-hand side operand are used.

Zac Roberts
Ranch Hand
Posts: 82
This answer is 56 because if you shift by more than your capacity then you have to shift by the modulus. What this means is that (7 << 32003) means we are shifting an int (7) which has a capacity of 32 bits. Well, 32003 is way more than our capacity of only 32 bits. So we have to take 32003 % 3 which gives 3 because of course % returns the remainder of 32003 divided by 3. So what we are really evaluating is (7 << 3) which is 56.
Zac

Joe Man
Ranch Hand
Posts: 71
I think i got the idea:
So the binary string for 32003 is:
111110100000011
Take 5 least-significant bits of the right-hand side operand:
000011 is 3
So 7*(2^3) = 56
My concern is this.. During the exam, if they give me 7<<33003 instead of 7<<32003, how would i be able to figure out the binary string for this large number and try to calculate the answer?

Joe Man
Ranch Hand
Posts: 71
Zac,
I'm not really following you. "So we have to take 32003 % 3 which gives 3 because of course % returns the remainder of 32003 divided by 3."
32003 % 3 is 2 not 3.
Can you please explain? thanks..

Zac Roberts
Ranch Hand
Posts: 82
Oops, Sorry, I was tired last night when I typed that response. I meant 32003 % 32 is 3. So we divide 32003 by the size of an int (32) and take the remainder which is 3.
Zac

Rob Ross
Bartender
Posts: 2205
That's why the Surgeon General of the United States warns sleep-deprived individuals against doing any math calculations.