.NET 移位运算符在数学应用场景下的说明
左移运算符 (
<<
) 将第一个操作数向左移动第二个操作数指定的位数。
所有移位都和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))
对于整型类型,
&
计算其操作数的逻辑按位 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))
...
....