Csharp/CSharp Tutorial/Operator/shift operator

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Shift Operators in action

<source lang="csharp">using System; class MainClass {

 static void Main(string[] args)
 {
   uint a = 0;
   uint b = 0;
   a = 8 << 3;
   
   Console.WriteLine(a);
   
   b = 32 >> 4;
   
   Console.WriteLine(b);
 }

}</source>

64
2

Shift Operators: shift left and right

<source lang="csharp">using System; class MainClass {

  static void Main()
  {
     int a, b, x = 14;
     a = x << 3;      // Shift left
     b = x >> 3;      // Shift right
     Console.WriteLine("{0} << 3 = {1}", x, a);
     Console.WriteLine("{0} >> 3 = {1}", x, b);
  }

}</source>

14 << 3 = 112
14 >> 3 = 1

The Shift Operators

  1. <<: Left shift
  2. >>: Right shift

The general forms for these operators are shown here:


<source lang="csharp">value < num-bits value > num-bits</source>

  1. A "left shift" shift all bits to the left and a zero bit to be brought in on the right.
  2. A "right shift" causes all bits to be shifted right one position.
  3. In the case of a right shift on an unsigned value, a zero is brought in on the left.
  4. In the case of a right shift on a signed value, the sign bit is preserved.