posted 22 years ago
When I think about bit shifting, I try to visualize a window that I'm sliding bits through. Take this example:
Let's try to follow what happens in each step. First, what does b look like in binary?
|00000111| // byte b in binary
I've added '|' characters to show the "edge of the window" that we'll be sliding our bits through. That window is the size of the data type, in this case, 8 bits. The binary representation between the two bars is what is actually stored in b.
Now, think about sliding the bits whichever direction the shift operator says to shift. In the first case, the shidt operator points to the left, so we'll shift left 1 space.
0|0000111?|
As you can see, to shift left, we simply moved all the bits one space to the left. That leaves a hole on the right side of the window. What do we fill that in with? When doing a left shift, we always fill with 0's. So, what does that give us?
0|00001110| = 14
Notice, shifting left 1 is equivalent to multiplying by 2.
Now, the next operator says that we should shift right two spaces. I'll show this in three steps, starting with what we had left from the last shift:
1. |00001110|
2. |?0000111|0
3. |??000011|10
As you can see, we're just moving the bits to the right. In this case, we moved the 10 on the right out of the window. Again, we're left with a hole on the left side of the window? What should we fill that with? This time, we need to make a decision. The operator used was '>>'. That's the right-shift with sign operator. That means we should keep the original sign of the number after the shift. The sign of the value is given by the leftmost bit. If it's a 0, the number is positive, if it's a 1, the number is negative. Since we started with a 0 as the leftmost bit, we'll shift in 0's (the leftmost bit shouldn't change when doing a right shift with sign). That gives us this:
|00000011| = 3
Just as left shifting by one bit is equivalent to multiplying by 2, right shifting by one is equivalent to dividing by 2. We shifted two places in this case, so we divided by 2*2 or 4. 14/4 = 3 (it's truncated, of course).
Now, for the final operation: v >>> 1. Let's start with what we had after the last operation and go from there:
|00000011|
|?0000001|1
Again, we slide the bits to the right, knocking that last 1 out of the window. Now, what shall we fill the hole on the left with? Well, this time the operator was '>>>'. That means that, no matter what, we're going to slide 0's in from the left. That means that, after a right shift without sign (assuming we don't shift by 0), the resulting value with always be positive. That leaves us with this:
00000001 = 1
The final value of b, after the three shifts, is 1.
I hope this explanation makes sense to you. It'd be a lot easier if I could just draw it for you. If you have any more questions, I can try to explain some more.
Corey