A question about bit shift operators. Assume I have the following:
int x = -8; //binary = 1000 0000 0000 0000 0000 0000 0000 1000
Now, if I perform the following operation:
x >>= 2;
I get a result of -2. However, I must be misunderstanding the dynamics of the >> operator. Doesn't it shift the sign bit to the right, keeping the original sign bit value in its place and replacing each bit to the right with the value of the sign bit? So the final binary representation should be the large (well, small really) negative number:
1110 0000 0000 0000 0000 0000 0000 0010
But it seems the >> operator, while preserving the sign bit, only shifts the bit in the 4th position (not the sign bit itself), resulting in -2.
Can anyone explain the actions of the >> operator further? Thanks for your attention,
Yours and my understanding of >> is the same (I'm not saying we're correct ), but I think your confusion is caused by how Java represents ints: with two's complement notation.
A very very brief intro: If you have a positive bit pattern say, 0000 1010 (int +ten, in 8-bit two's complement), you get its corresponding negative by flipping the bits and adding one. So, in this case we flip the bits to '1111 0101', and add one to get '1111 0110'. That last pattern is -ve ten, in two's complement.
In any case, you can Google for a better explanation or just play around with it yourself: