#1,114 – Don’t Use Shift Operators to Do Multiplication

When you use the shift operators on integer-based values, you effectively multiply a number by two when you do a left shift by one bit and divide a number by two when you do a right shift by one bit.

In years past, you’d sometimes hear a recommendation that you should prefer using the shift operators over multiplicative operators because the shift operators were faster.

With modern optimizing compilers, you should no longer worry about this level of optimization and performance.  If you need to multiply a number by a power of two, you should express your intent by using the multiplicative operators.  (E.g. “* 2” or “* 4”).  The compiler will figure out that fastest way to accomplish this.

Advertisements

#75 – New Bits When Shifting

When doing bitwise shifting using the << and >> operators, the data value being shifted will always shift new bits in–from the left when right shifting, or from the right when left shifting.  The value of the new bits depend on the direction of the shift and the data type being shifted.

  • Right shift
    • If shifting int or long, new bits at left match sign of the value
    • If shifting uint or ulong, new bits at left are 0-valued
  • Left shift
    • New bits at right are 0-valued

Shift operations can never result in an overflow.