I l@ve RuBoard |
![]() ![]() |
11.6 The Left and Right Shift Operators (<<, >>)The left shift operator moves the data left a specified number of bits. Any bits that are shifted out the left side disappear. New bits coming in from the right are zeros. The right shift does the same thing in the other direction. For example:
Shifting left by one (x << 1) is the same as multiplying by 2 (x * 2). Shifting left by two (x << 2) is the same as multiplying by 4 (x * 4, or x * 22). You can see a pattern forming here. Shifting left by n places is the same as multiplying by 2n. Why shift instead of multiply? Shifting is faster than multiplication, so: i = j << 3; // Multiply j by 8 (2**3) is faster than: i = j * 8; Or it would be faster if compilers weren't smart enough to turn "multiply by power of two" into "shift." Many clever programmers use this trick to speed up their programs at the cost of clarity. Don't do it. The compiler is smart enough to perform the speedup automatically. This means that putting in a shift gains you nothing at the expense of clarity. The left shift operator multiplies; the right shift divides. So: q = i >> 2; is the same as: q = i / 4; Again, this clever trick should not be used in modern code. 11.6.1 Right Shift DetailsRight shifts are particularly tricky. When a variable is shifted to the right, C++ needs to fill the space on the left side with something. For signed variables, C++ uses the value of the sign bit. For unsigned variables, C++ uses zero. Table 11-7 illustrates some typical right shifts.
|
I l@ve RuBoard |
![]() ![]() |