programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
• Campbell Ritchie
• Paul Clapham
• Ron McLeod
• Liutauras Vilda
• Bear Bibeault
Sheriffs:
• Jeanne Boyarsky
• Tim Cooke
• Devaka Cooray
Saloon Keepers:
• Tim Moores
• Tim Holloway
• Piet Souris
• salvin francis
• Stephan van Hulst
Bartenders:
• Frits Walraven
• Carey Brown
• Jj Roberts

# Right shift operators

Ranch Hand
Posts: 224
Hi i get confused when it comes to shift operator

From my understanding
Number to be shifted is always left operand
the number of bits to be shifted is always right operand
In this your number of bits to be shifted is greater thn actual number
so we use formulae
32%2=0 then we use 0>>>2 and 0>>2= 0/2pow2=0
0 is my ans
but when i compile and run the application i get following ans

1073741823
-1

Please explain me where i have gone wrong

Sheriff
Posts: 11343

...In this your number of bits to be shifted is greater thn actual number
so we use formulae
32%2=0 then we use 0>>>2 and 0>>2= 0/2pow2=0
0 is my ans...

I think what you're looking for is something like: If the amount of the shift (the right-hand operand) is greater than the number of bits in the type (32 for int, or 64 for long), then shift by the remainder after division by the number of bits in the type.

For example, if x is an int, then for x >>> 35, you would use x >>> (35%32), which is x >>> 3.

Technically, for int shifting, only the last 5 bits of the right-hand operand are used, so the shift will always be between 0 and 31 inclusively (even if the right-hand operand is negative). For long shifting, only the last 6 bits of the right-hand operand are used, so the shift will always be between 0 and 63 inclusively.

Also, note that bit shifting is on the 1.4 exam, but not on the 1.5 exam.

Ranch Hand
Posts: 44
I know that with the 2nd one (-1 >> 2) should give -1...ie.
(-1 >> a number = -1)

Cheryl Gray
Ranch Hand
Posts: 44
Also, for the 1st one, (-1>>>2) I know that the answer will be a positive number since the >>> produces a sign change if the number, in this case
(-1), is a negative number.

marc weber
Sheriff
Posts: 11343

Originally posted by Cheryl Gray:
Also, for the 1st one, (-1>>>2) I know that the answer will be a positive number since the >>> produces a sign change if the number, in this case (-1), is a negative number.

Unless the shift distance (the right operand) is divisible by the number of bits in the (possibly widened) type of the left operand. In that case, the result will be -1, because the shift distance will be zero.