Imagine a bit string as represented by the following group of boxes.
Every box represents a bit, a binary digit; the ones and zeros inside
represent their values. The values written across the top are
the place-values of each bit. (Just as a decimal (base-10) number has
a ones place, a tens place, a hundreds place, a thousands place, and so on,
a binary (base-2) number has the places 1, 2, 4, 8, 16, 32, etc.)
The number after the equals sign shows the value of the bit string in
decimal notation.
Bit-shift operators move whole bit strings left or right.
The syntax of the bit-shift left operation is value << positions;
that of bit-shift right is value >> positions;
So for example, using the bit string (1) above, the value of 1 << 1 is 2,
because the bit string would have been moved one position to the left:
Notice that every shift left multiplies by 2. (Since 6 << 2 means to shift 6 left twice,
the result is 24.)
As you might expect, every shift right performs (integer) division by two on the number.
If a bit is shifted beyond the ones position (the rightmost "box"), however,
then it "drops off" and is lost. So the following equalities hold:
1 >> 1 == 0
2 >> 1 == 1
2 >> 2 == 0
n >> n == 0
One common use of bit-shifting is to scan through the bits of a bit-string
one by one in a loop. This is done with bit masks, as described in the next section.