int result1= 66 << 1;//正数的左移位运算规则,左移一位乘以2,右移移位除以2 左移两位乘以4,三位乘以8,4位乘以16,右移则相反; int result2 = -66<< 1; //负数的移位运算在最高位补1;运算规则和正数一样 Console.WriteLine("正数移位"+result1+"............"+"负数移位"+result2);
当声明重载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); } } }