Team LiB
Previous Section Next Section

Shift Operators

The shift operators are used to shift bits either left or right, essentially performing a multiplication or division operation.

Shift Left

The shift left operator (<<) shifts bits to the left. The bits of the left operand are the integral number of positions specified to the right operand. As bits are shifted left, the low-order bits are brought to zero. Bits shifted beyond the high-order bits are lost. This basically means that you multiply the value by a power of 2. For example, a = 8 << 3 really means 8 × 2^3.

Shift Right

The shift right operator (>>) performs the same operation as the shift left operator, but the bits are shifted right. If the value being shifted is unsigned, the value of the leftmost bit is set to zero; otherwise, it is set as the sign bit. This means you divide the number by a power of 2. For example, a = 32 >> 4 really means 32/2^4.

The following is an example of using the shift operators.

Code Example: Shift Operators
Start example

using System;

namespace Client.Chapter_2___ Expressions_and_Operators
{
      class ShiftOperators
      {
            static void Main(string[] args)
            {
                  uint a = 0;
                  uint b = 0;
                  //a = 64
                  a = 8 << 3;
                  //b = 2
                  b = 32 >> 4;
            }
      }
}
End example

Team LiB
Previous Section Next Section