This week's book giveaway is in the Kotlin forum.
We're giving away four copies of Kotlin in Action and have Dmitry Jemerov & Svetlana Isakova on-line!
See this thread for details.
Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Shifting by negative values  RSS feed

 
Subramaniam Govindasamy
Greenhorn
Posts: 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Can any body help about shifting a integer left or right by a negative number.For example 4<<-2.
Here 4<<-2 gives 0.But 4<<-3 and so on gives non zero values(negative numbers also ).Justify this operation.
 
Henry Wong
author
Sheriff
Posts: 23283
125
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Originally posted by Subramaniam Govindasamy:
Can any body help about shifting a integer left or right by a negative number.For example 4<<-2.
Here 4<<-2 gives 0.But 4<<-3 and so on gives non zero values(negative numbers also ).Justify this operation.


First of all...



Anyway, there is not such thing as shifting by a negative number. When you shift an integer, only the lowest 5 bits are used. Hence, shifting by -2 is the same as shifting by 30. And shifting by -3 is the same as shifting by 29.

So...



Henry
 
marc weber
Sheriff
Posts: 11343
Java Mac Safari
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
...and when you shift by a long, only the lowest 6 bits are used.

Thus, not only is the shift quantity never negative, but it's always less than 32 for an int and less than 64 for a long.
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!