Take it easy. If you look in the
Java™ Tutorial, you find this:
Certain operators tend to appear more frequently than others; for example, the assignment operator "=" is far more common than the unsigned right shift operator ">>>".
So you needn't expect to find lots of questions about shift operators.
You usually use them on ints mainly because ints are the most popular type of number, but I shall show you how they work on bytes, mainly because it is quicker to write 8 1s than 32!
1: The left-shift operator. <<
n
This moves the whole thing
n bits to the left; any bits which pass the most significant bits disappear into cyber-limbo and any gaps on the right are filled with 0s. So 21 << 2 is
21 = 00010101Two to the left = 010101--Fill in the 0s = 01010100Convert to decimal = 84.84 / 21 = 4, and 4 = 2². There's your 2 back.Left-shift 1 bit is equivalent to multiplying by 2, two bits is multiplying by 4, and three bits is multiplying by 8.
The normal rules about overflow errors apply; 21 << 3 in 32 bits is 168 but in 8 bits it's -88. -33 << 2 in 32 bits is -132, in 8 bits it's +124.
2: The right-shift operator >>
n
This moves the whole thing
n bits to the right; any bits which pass the least significant bit fall off the edge of the world and it fills in from the left with
the same bit that the original most significant bit was. 21 >> 2 is
21 = 000101012 to the right gives --000101Fill in with 0 gives 00000101and that's 521 / 5 in integer arithmetic is 4, 4 = 2^2, and there's your 2 back.Not 168, but -88 is 10101000.2 to the right gives --101010Fill in with 1s this time gives 1110101011101010 is -22.-88 / -22 is 4, and 4 is 2².So right-shift by 1 is the same as dividing by 2, two bits to the right is the same as dividing by 4, three bits is dividing by 8, etc. Note that the sign is always maintained and there is no risk of overflow, but if you shift too many places you will always get -1 from negative numbers and 0 from positive numbers.
Both the right-shift and left-shift operators are usually described as being "signed."
3: The unsigned right shift >>>
n
This is the most complicated of the three. It moves the bits
n places to the right, and any bits which pass the least significant bit float off into the wild blue yonder, but it fills in from the left with 0s. So it
always returns a positive answer, whether the original answer was positive or negative. For positive numbers it has exactly the same effect as the ordinary signed right-shift, so I won't draw it
For a negative number, eg -88 >>> 2, this is what happens
-88 is 10101000Two to the right gives --101010Fill in with ZEROES from the left: 0010101000101010 is 42.
Remember that is you multiply 42 by 4 in 8 bits you get -88. I am afraid I can't think of a simple way to calculate the values you get from a >>> operator.
I hope this is of some help to you
And it was a nice interesting question to answer, too.
[edit]Correct 84 / 2 = 5 to 84 / 21 = 5 and change ^2 to superscript 2 twice.[/edit]