Node:Shift operations, Next:, Previous:Bitwise operators, Up:Machine-level operators



Shift operations

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.

 128  64  32  16  8   4   2   1
 -------------------------------
| 0 | 0 | 0 | 0 | 0 | 0 | 0 | 1 |  =  1
 -------------------------------

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:

 128  64  32  16  8   4   2   1
 -------------------------------
| 0 | 0 | 0 | 0 | 0 | 0 | 1 | 0 |  =  2
 -------------------------------

Notice how the space to the right of the shifted bit string is simply filled with a 0.

Similarly, the value of 1 << 4 is 16, because the original bit string is shifted left four places:

 128  64  32  16  8   4   2   1
 -------------------------------
| 0 | 0 | 0 | 1 | 0 | 0 | 0 | 0 |  =  16
 -------------------------------

Notice, again, that the spaces to the right of the original bit string are filled out with zeros.

Now for a slightly more difficult one. The value of 6 << 2 is 24. Here is the bit string representing 6:

 128  64  32  16  8   4   2   1
 -------------------------------
| 0 | 0 | 0 | 0 | 0 | 1 | 1 | 0 |  =  6
 -------------------------------

Shift 6 left 2 places:

 128  64  32  16  8   4   2   1
 -------------------------------
| 0 | 0 | 0 | 1 | 1 | 0 | 0 | 0 |  =  24
 -------------------------------

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.