posted by Poorna:
Hai Shishio San,
You have told that if x >> y means, x >> y%32, but why is like that ?
That is how compiler will treat right shift.
Also, a while ago someone posted a request that if there is an easier way to solve these shifting questions without actually finding the binary equavalent and shifting and finding decimal equivalent. I put together an alternative. I found it accurate. What do you guys think:
Shift Operators
A op B
Assuming A is any integral value except long. For long A, replace 32 with 64:
1. B = B%32
2. If B is negative and not –32 : B=B+32
3. For signed right shift operator (>>
, divide A successively by 2, B number of times. Round down the final result if A is positive. Round up the final result if A is negative.
4. For signed left shift operator (<<
; multiply A succesively by 2, B number of times. If (32-B)th bit of original A value is 1, make the result –ve if it is not already negative. If the final result is more than Integer.MAX_VALUE, make final result 0.
5. For unsigned right shift operator (>>>
with postive A, same rules as number 3 above.
6. For unsigned right shift operator (>>>
with negative A, do it conventional way:
a. find the 2’s compliment of negative A
b. right shift by B bits, inserting 0 on the left
c. find the decimal of above.
Examples:
int A = 200, B = 2
A >> B;
1. B=B%32 => B=2
2. B=2
3. result=50
Try more for yourself. Let me know if you have any questions.
Thanks
Barkat