<< 運算子 (C# 參考)<< Operator (C# Reference)

左移運算子 (<<) 會向其第一個運算元左移第二個運算元所指定的位元數。The left-shift operator (<<) shifts its first operand left by the number of bits specified by its second operand. 第二個運算元的類型必須是 int 或對 int 進行預先定義隱含數值轉換的類型。The type of the second operand must be an int or a type that has a predefined implicit numeric conversion to int.

備註Remarks

如果第一個運算元是 intuint (32 位元數量),則是由第二個運算元的低序位五位元指定移位計數。If the first operand is an int or uint (32-bit quantity), the shift count is given by the low-order five bits of the second operand. 也就是,實際移位計數是 0 到 31 位元。That is, the actual shift count is 0 to 31 bits.

如果第一個運算元是 longulong (64 位元數量),則是由第二個運算元的低序位六位元指定移位計數。If the first operand is a long or ulong (64-bit quantity), the shift count is given by the low-order six bits of the second operand. 也就是,實際移位計數是 0 到 63 位元。That is, the actual shift count is 0 to 63 bits.

會捨棄移位後面不在第一個運算元類型範圍內的任何高序位位元,而且低序位空位元都會填入零。Any high-order bits that are not within the range of the type of the first operand after the shift are discarded, and the low-order empty bits are zero-filled. 移位作業絕不會造成溢位。Shift operations never cause overflows.

使用者定義型別可以多載 << 運算子 (請參閱 operator);第一個運算元的類型必須是使用者定義型別,而第二個運算元的類型必須是 intUser-defined types can overload the << operator (see operator); the type of the first operand must be the user-defined type, and the type of the second operand must be int. 二元運算子多載時,對應的指派運算子 (若有) 也會隱含地多載。When a binary operator is overloaded, the corresponding assignment operator, if any, is also implicitly overloaded.

範例Example

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
*/

註解Comments

請注意,i<<1i<<33 提供相同的結果,因為 1 和 33 有相同的低序位五位元。Note that i<<1 and i<<33 give the same result, because 1 and 33 have the same low-order five bits.

請參閱See Also