C#移位运算(左移和右移)
2020-07-14 04:48
656 查看
园子里大牛太多了,几乎写什么类型的文章都会有人写过,大牛们写过的东西,偶不写,好象还没那个功力吧。
今天写一个比较有意思的东西 -- 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的幂次方的乘除运方,可以采用位移的方式进行。
比较有意思吧?
转载于:https://www.cnblogs.com/kakimsun/archive/2010/04/27/1722403.html
相关文章推荐
- C#移位运算(左移和右移)
- C#移位运算(左移和右移)
- C#中的移位运算
- C#移位运算的典型事例
- C#移位运算(左移和右移)
- C#移位运算(左移和右移)
- 用最有效率的方法算出2乘以8等于几?(C#移位运算)
- C#中的运算(移位、异或、与、或)
- C#中的移位运算
- C#运算符之与,或,异或及移位运算
- C#上机 第八周 任务8 移位运算来避免乘法运算
- 《使用移位运算来避免乘法运——C#第八周》
- C#移位运算(左移和右移)
- C#运算符之与,或,异或及移位运算
- C#运算符之与,或,异或及移位运算
- C#移位运算(左移和右移)
- C陷阱篇之移位运算
- 关于java移位运算
- C#中的&运算
- 布尔运算 逻辑运算 移位运算