• 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(510);
    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的幂次方的乘除运方,可以采用位移的方式进行。

  • 相关阅读:
    JSON就是名值对 name/value pair
    AjaxXMLHttpRequest
    英语单词分类记
    委托和事件的理解
    用float设置主页的左右两边菜单
    OCS通讯路径
    测试用Word写Blog
    第一课 C#入门
    nginx虚拟目录设置 alias 和 root
    vsftp 出错,无法创建文件的解决方法
  • 原文地址:https://www.cnblogs.com/wwwzzg168/p/3570152.html
Copyright © 2020-2023  润新知