#74 – Shift Operators

C# supports two bitwise shift operators that allow you to shift a series of bits a certain number of bit positions to the left or right.

  • <<    Left shift
  • >>    Right shift

The shift operators work on the following types: uint, int, ulong, and long.

 uint u = 0x32 << 4;    // Shift 4 bits to left = 0x320
 uint u2 = 0xAB0 >> 4;  // Shift 4 bits to right = 0xAB

Note that shifting to the left is the same as multiplying the value by 2 to the power of the # of bits shifted.  E.g. Shifting by 1 bit doubles the number and shifting by 2 bits multiples the number by 4.

 uint u = 12 << 1;      // 24
 u = u << 3;            // * 8 = 192

Similarly, shifting to the right divides the value by 2 to the power of the # of bits shifted.

Advertisements