NET 移位
2018-09-13

0X1 摘要

.NET 移位运算符在数学应用场景下的说明

0X2 移位运算符

MS Docs

0X3 << 运算符

左移运算符 (<<) 将第一个操作数向左移动第二个操作数指定的位数。

所有移位都和2的多少次幂有关系,所以pow(幂)也有了范围比如 int.MaxValue=2^32 所以int下pow的范围是[0-31]

  • 转换为乘法
    void shiftRight(int x, int pow)
    {
      int c = (int)Math.Pow(2, pow);
      int a = x * c;
      int b = x << pow;
      System.Diagnostics.Debug.Assert(a == b);
    }
    可以得出 (x << pow)==(x*(int)Math.Pow(2, pow))

##0X3 >> 运算符

右移运算符 (>>) 将第一个操作数向右移动第二个操作数指定的位数。

  • 转换为除法
    void shilfLeft(int x, int pow)
    {
      int c = (int)Math.Pow(2, pow);
      int a = x / c;
      int b = x >> pow;
      System.Diagnostics.Debug.Assert(a == b);
    }
    可以得出 (x >> pow)==(x/(int)Math.Pow(2, pow))

0X4 & 运算符

对于整型类型,& 计算其操作数的逻辑按位 AND

对于整数类型可以理解为求余数,但是底数必须是(2^pow)

  • 转换为求余
    void shiftAnd(int x, int pow)
    {
      int c = (int)Math.Pow(2, pow);
      int a = x % c;
      int b = x & (c - 1);
      System.Diagnostics.Debug.Assert(a == b);
    }
    当底数为c=(2^pow)时,( x % c)=( x & (c-1))

0X5 ^ 运算符

...

0X6 | 运算符

....