Shift operations
The shift left and shift right operations take the binary form of a decimal number and shift the digits left or right, respectively. Then they return the decimal form of the new binary number.
For example, the decimal number 14 in binary, padded to 8 digits, is 00001110. Shifting this left by two places results in 00111000, which is 56 in decimal.
Here’s an illustration of what happens during this shift operation:
The digits that come in to fill the empty spots on the right become 0. The digits that fall off the end on the left are lost.
Shifting right is the same, but the digits move to the right. The operators for these two operations are as follows:
- Shift left: <<
- Shift right: >>
These are the first operators you’ve seen that contain more than one character. Operators can contain any number of characters, in fact.
Here’s an example that uses both of these operators:
1 << 3
32 >> 2
Both of these values equal the number 8.
One reason for using shifts is to make multiplying or dividing by powers of two easy. Notice that shifting left by one is the same as multiplying by two, shifting left by two is the same as multiplying by four, and so on. Likewise, shifting right by one is the same as dividing by two, shifting right by two is the same as dividing by four, and so on.
In the old days, code often made use of this trick because shifting bits is much simpler for a CPU to do than complex multiplication and division arithmetic.
Therefore the code was quicker if it used shifting. However these days, CPUs are much faster and compilers can even convert multiplication and division by powers of two into shifts for you. So you’ll see shifting only for binary twiddling, which you probably won’t see unless you become an embedded systems programmer!