Bitwise ShiftsThere are two bitwise shift operators, namely shift left and shift right. In C, they are represented by the << and >> operators, respectively. These operations are very simple, and do exactly what they say: shift bits to the left or to the right. The syntax for a shift operation is as follows: [integer] [operator] [number of places]; A statement of this form shifts the bits in [integer] by the number of places indicated, in the direction specified by the operator. Probably the best way to visualize this is with an example. Take a look at the following code, which demonstrates a shift left. // Precondition: x == 0000 0110 1001 0011 // Postcondition: y == 0000 1101 0010 0110 x = x << 1; From this example, you should be able to see what's going on. Every bit in x is shifted to the left by one place. When you do this, the MSB (most significant bit, remember?) of x is lost, because there isn't another place to shift it to. Similarly, after a shift left, the LSB of x will always be 0. There is no position to the right of the LSB, and so there's nothing to shift into the LSB, so it's assigned a value of 0. Just to make sure you've got the idea of this, let's take a look at a shift right: // Precondition: x == 0110 1111 1001 0001 // Postcondition: y == 0000 0110 1111 1001 x = x >> 4; Here, the bits are being shifted right by four places. Got it? Good. That finishes out the set of bitwise operators, so now we can finally get around to seeing what they're good for. |