jehn

C#移位运算(左移和右移)

今天写一个比较有意思的东西 --  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的幂次方的乘除运方,可以采用位移的方式进行。

  比较有意思吧?

posted on 2011-11-07 11:21  jehn  阅读(494)  评论(0编辑  收藏  举报

导航