Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# Shortcut and shift operators

Mamta
Greenhorn

Joined: Oct 05, 2000
Posts: 13
Are there any quick ways to calculate the results of expressions involving shift operators and/or shortcut operators. E.g. How do you solve an expression like
0xFF >> 22
in the fastest way possible?
regds,
Mamta
Anonymous
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944

The following link might give you some insight...
http://www.javaranch.com/ubb/Forum24/HTML/001272.html
Best of luck.
Regds.
- satya
Herbert Maosa
Ranch Hand

Joined: May 03, 2000
Posts: 289
Also I think you can quickly try to minimize your selection by eliminating the obviously wrong answers. That is you know that << and >> are signed, therefore you can quickly disregard answers that show a changed sign. Then you know that >>> is unsigned, then you know that you can never have a -ve result after performing >>>, so you can quickly eliminate or answers that show -ve after >>>. I hope this might help a bit.

Good luck
Herbert.
kking
Ranch Hand

Joined: Mar 14, 2000
Posts: 30
You won't be asked any large unusual numbers like 22.
However, for numbers greater than or equal to 31, an easy way is to subtract 31 and then calculate the answer. For example
-1 >> 33 is the same as -1 >> (33 - 31) or -1 >> 2
Then the calculation is easy.
Hope this helps!
Herbert Maosa
Ranch Hand

Joined: May 03, 2000
Posts: 289
Just to add more to what Kking is saying. In case you are wondering how the subtraction comes from.
If the left operand is an int, then you know that you can only do a shift 0 through 31 times since an int has size 32 in bits. so if the right operand exceeds 31, you know that it goes over the bit size, then the actual number of shifts will be (right operand % 32). So in the case of 33, it would be 33%32, which is 1. So you actually would shift 1 time( I hope Kking will review his subtraction and verify this). Another way to consider it is to say that if the left operand is an int, then only the last five bits of the right operand will be used for the shift. So for 33, we can write it in binary as :
1 0 0 0 0 1
and the last five bits are :
0 0 0 0 1
which is decimal 1. so we shift 1 time.

Herbert.
Mamta
Greenhorn

Joined: Oct 05, 2000
Posts: 13
Thanks guys, that was a great help!!!
How well do you have to score in Mock tests before you go for the actual SCJP exam ? I thought I was pretty well prepared (Except for these shift operators of course ) but when I took some tough Mock exams I found that my score is just average . Do you really need to score in the 80's and 90's in mock tests before you take the ultimate plunge?