• Post Reply Bookmark Topic Watch Topic
  • New Topic

shift operators  RSS feed

 
Sharada Kumaran
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do shift operators work when the right operand is negative? for instance, how is the value calculated for
int result = 12 << -3;
 
mousami bhattacharya
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
What I do is
12 << -3 <br /> take the last 5 bits (when LHS is int) --> 1 1101<br /> treat this as a normal +ve number<br /> 0001 1101 ---> 0x1D -- > 29
Now 12 is --> 0000 .....0000 1100
So its 000 ....0000 1100 << 29<br /> If you do this you'll find the most significant bit gets the 1<br /> --> 1000 ....0000 ... ---> -2147483648 or Integer.MIN_VALUE
This is the way I do and the answers come out right .I dont know whether its the correct method or not.
Can any one confirm if I am doing the right thing here..
Mousami
 
Sharada Kumaran
Greenhorn
Posts: 29
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Wow, Mousami. That logic does work. but how did you get such a method? And what is the reasoning behind it. How does it work?
Anyway, I will use yr method. feel more confident about handling bit shifts. Do you know if there are questions in the certification on shift operations on floats/doubles? Does it make sense, 'coz i haven't seen such questions.
Thanks for the interesting solution.
 
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!