C#移位元運算(左移和右移)

來源:互聯網
上載者:User

  園子裡大牛太多了,幾乎寫什麼類型的文章都會有人寫過,大牛們寫過的東西,偶不寫,好象還沒那個功力吧。

  今天寫一個比較有意思的東西 --  C#移位元運算(左移和右移)。

  C#是用<<(左移) 和 >>(右移) 運算子是用來執行移位元運算。

  左移 (<<) 

  將第一個運算元向左移動第二個運算元指定的位元,空出的位置補0。
  左移相當於乘. 左移一位相當於乘2;左移兩位相當於乘4;左移三位相當於乘8。

  x<<1= x*2
  x<<2= x*4
  x<<3= x*8
  x<<4= x*16

  同理, 右移即相反:

  右移 (>>)
  將第一個運算元向右移動第二個運算元所指定的位元,空出的位置補0。

  右移相當於整除. 右移一位相當於除以2;右移兩位相當於除以4;右移三位相當於除以8。

  x>>1= x/2
  x>>2= x/4
  x>>3= x/8
  x>>4=x/16

  當聲明重載C#移位元運算符時,第一個運算元的類型必須總是包含運算子聲明的類或結構,並且第二個運算元的類型必須總是 int,如:

  

    class Program
{
static void Main(string[] args)
{
ShiftClass shift1 = new ShiftClass(5, 10);
ShiftClass shift2 = shift1 << 2;
ShiftClass shift3 = shift1 >> 2;

Console.WriteLine("{0} << 2 結果是:{1}", shift1.valA, shift2.valA);
Console.WriteLine("{0} << 2 結果是:{1}", shift1.valB,shift2.valB);
Console.WriteLine("{0} >> 2 結果是:{1}", shift1.valA, shift3.valA);
Console.WriteLine("{0} >> 2 結果是:{1}", shift1.valB, shift3.valB);

Console.ReadLine();
}

public class ShiftClass
{
public int valA;
public int valB;

public ShiftClass(int valA, int valB)
{
this.valA = valA;
this.valB = valB;
}

public static ShiftClass operator <<(ShiftClass shift, int count)
{
int a = shift.valA << count;
int b = shift.valB << count;
return new ShiftClass(a, b);
}

public static ShiftClass operator >>(ShiftClass shift, int count)
{
int a = shift.valA >> count;
int b = shift.valB >> count;
return new ShiftClass(a, b);
}

}
}

 

  以上運算式,輸出結果是:

 

 

  因為位移比乘除速度快.對效率要求高,而且滿足2的冪次方的乘除運方,可以採用位移的方式進行。

  比較有意思吧?

 

 

 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.