<< 运算符(C# 参考)

左移运算符 (<<) 将第一个操作数向左移动第二个操作数指定的位数。第二个操作数的类型必须是一个 int 或具有向 int 的预定义隐式数值转换的类型。

备注

如果第一个操作数是 intuint(32 位数),则移位数由第二个操作数的低 5 位给出。也就是实际的 shift 计数为 0 到 31 位。

如果第一个操作数是 longulong(64 位数),则移位数由第二个操作数的低 6 位给出。也就是实际的 shift 计数为 0 到 63 位。

不在移位后第一个操作数类型范围内的任意高序位均不会使用,低序空位用零填充。移位操作从不导致溢出。

用户定义的类型可重载 << 运算符(请参见操作数);第一个操作数的类型必须为用户定义的类型,第二个操作数的类型必须为 int。重载二元运算符时,也会隐式重载相应的赋值运算符(如果有)。

class MainClass11
{
    static void Main()
    {
        int i = 1;
        long lg = 1;
        // Shift i one bit to the left. The result is 2.
        Console.WriteLine("0x{0:x}", i << 1);
        // In binary, 33 is 100001\. Because the value of the five low-order
        // bits is 1, the result of the shift is again 2\. 
        Console.WriteLine("0x{0:x}", i << 33);
        // Because the type of lg is long, the shift is the value of the six
        // low-order bits. In this example, the shift is 33, and the value of
        // lg is shifted 33 bits to the left.
        //     In binary:     10 0000 0000 0000 0000 0000 0000 0000 0000 
        //     In hexadecimal: 2    0    0    0    0    0    0    0    0
        Console.WriteLine("0x{0:x}", lg << 33);
    }
}
/*
Output:
0x2
0x2
0x200000000
*/

注释

请注意,i<<1 和 i<<33 给出的结果相同,因为 1 和 33 的低序 5 位相同。

请参阅

C# 参考

C# 编程指南

C# 运算符