I l@ve RuBoard Previous Section Next Section

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:

 

c=0x1C

00011100

c << 1

c=0x38

00111000

c >> 2

c=0x07

00000111

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 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 10102 >> 2

1111 10002 >> 2

1111 10002 >> 2

Result

??00 00102

??11 11102 >> 2

??11 11102 >> 2

Fill

Sign bit (0)

Sign bit (1)

Zero

Final result (binary)

0000 00102

1111 11102

0011 11102

Final result (short int)

2

-2

62

    I l@ve RuBoard Previous Section Next Section