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 2
n
. 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 Details
Right 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.
Table 11-7. Right shift examples
|
|
Signed character
|
Signed character
|
Unsigned character
|
|
Expression
|
9 >> 2
|
-8 >> 2
|
248 >> 2
|
|
Binary value >> 2
|
0000 1010
2
>> 2
|
1111 1000
2
>> 2
|
1111 1000
2
>> 2
|
|
Result
|
??00 0010
2
|
??11 1110
2
>> 2
|
??11 1110
2
>> 2
|
|
Fill
|
Sign bit (0)
|
Sign bit (1)
|
Zero
|
|
Final result (binary)
|
0000 0010
2
|
1111 1110
2
|
0011 1110
2
|
|
Final result (short int)
|
2
|
-2
|
62
|