Hey there's ome problem now.Though I tried hard to understand the concept of shift operators, I am nt getting it.I tried various resources , RHE, other Tuts, etc..but all in vain,Can you suggest me in this matter..I simply cannot understand (<<,>>,>>> , stuffs..
I wouldn't worry too much about it but here goes:
First, I would read the following article at Javaranch explaining how
to manipulate bits:
http://www.javaranch.com/campfire/StoryBits.jsp Then as you already know all integral types are basically represented in binary by bits, for instance the number 25 is 00011001 in binary.
Now the shift operators allow you to modify those binary-represented numbers by shifting to the left or to the right the bits composing the number. On the left side you put the number and on the rigth side you put the number of shift step you want to achieve, for instance:
in 25 >>> 2 we want to shift the bits representation of 25 two steps to the right. Now to do this, you just take the binary representation of 25 and shift its bit
pattern two steps to the right, like this:
00011001 >>> 2 = 00000110 = 6. That is 25 shifted 2 steps to the right is 6.
I think you got it.
Now >> can be tricky. Remember that we just added some 0's on the left side to pad it when shifting to the right side with >>>. With >> it's different, you don't add 0's but the value that is presently the first bit (on the left) before the shift. For instance:
25 >> 2 = 00011001, we have a 0 as the first left bit so we pad 0's like this: 00000110 = 6. Same result as before. But in 11001000 >> 2 we have a 1 as the first bit on the left, so we pad 1's, like this: 11110010.
The main difference between >> and >>> is that we say the first is SIGNED and the second is UNSIGNED. When you deal with negative numbers (that is numbers whose first bit is 1 which indicates a minus sign) the operator >> keeps the sign of the number (because it adds 0 if the first bit is 0, that is the number is and stays positive, and adds 1 if the first bit is 1, that is the number is and stays negative) while >>> doesn't since it adds 0's regardless of what the sign bit is.
A last remark is that the right-hand side of the operator is carefully examined before the shifting. If the number on the left is an int, then the number on the right (that is the shift steps) cannot be bigger than 32 because an
int has 32 bits and it doesn't make sense to shift more than the number can be shifted. As well, if the left-hand side is a long, then the right hand side cannot be bigger than 64 because, again, it doesn't make sense to shift a long for more than 64 bits. So the right hand side is first truncated to 32 (right-hand modulo 32) or 64.
HIH
[ January 19, 2002: Message edited by: Valentin Crettaz ]