11.6 The Left and Right Shift Operators (, )

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:

 

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

I l @ ve RuBoard


Practical C++ Programming
Practical C Programming, 3rd Edition
ISBN: 1565923065
EAN: 2147483647
Year: 2003
Pages: 364

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net