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

左移運算子 (<<) 會向其第一個運算元左移第二個運算元所定義的位元數。The left-shift operator << shifts its first operand left by the number of bits defined by its second operand. 所有整數型別都支援 << 運算子。All integer types support the << operator. 不過,第二個運算元的類型必須是 int 或對 int 進行預先定義隱含數值轉換的類型。However, the type of the second operand must be int or a type that has a predefined implicit numeric conversion to int.

位於結果型別範圍以外的高位位元會被捨棄,而且低位空位元位置會被設定為零,如下列範例所示:The high-order bits that are outside the range of the result type are discarded, and the low-order empty bit positions are set to zero, as the following example shows:

uint x = 0b_1100_1001_0000_0000_0000_0000_0001_0001;
Console.WriteLine($"Before: {Convert.ToString(x, toBase: 2)}");

uint y = x << 4;
Console.WriteLine($"After:  {Convert.ToString(y, toBase: 2)}");
// Output:
// Before: 11001001000000000000000000010001
// After:  10010000000000000000000100010000

位移計數Shift count

針對運算式 x << count,實際位移計數相依於 x 的型別,如下所示:For the expression x << count, the actual shift count depends on the type of x as follows:

  • x 的型別為 intuint,則位移計數是由第二個運算元的低位五個位元所給定。If the type of x is int or uint, the shift count is given by the low-order five bits of the second operand. 也就是說,位移計數是從 count & 0x1F (或 count & 0b_1_1111) 所計算。That is, the shift count is computed from count & 0x1F (or count & 0b_1_1111).

  • x 的型別為 longulong,則位移計數是由第二個運算元的低位六個位元所給定。If the type of x is long or ulong, the shift count is given by the low-order six bits of the second operand. 也就是說,位移計數是從 count & 0x3F (或 count & 0b_11_1111) 所計算。That is, the shift count is computed from count & 0x3F (or count & 0b_11_1111).

下列範例示範了該行為:The following example demonstrates that behavior:

int a = 0b_0001;
int count1 = 0b_0000_0001;
int count2 = 0b_1110_0001;
Console.WriteLine($"{a} << {count1} is {a << count1}; {a} << {count2} is {a << count2}");
// Output:
// 1 << 1 is 2; 1 << 225 is 2

備註Remarks

位移作業一律不會導致溢位並產生已選取與未選取內容的相同結果。Shift operations never cause overflows and produce the same results in checked and unchecked contexts.

運算子是否可多載Operator overloadability

使用者定義型別可以多載 << 運算子。User-defined types can overload the << operator. 若使用者定義型別 T 會多載 << 運算子,則第一個運算元的型別必須是 T,且第二個運算元的型別必須是 intIf a user-defined type T overloads the << operator, the type of the first operand must be T and the type of the second operand must be int. 多載 << 運算子時,左移指派運算子 <<=也會隱含地多載。When the << operator is overloaded, the left-shift assignment operator <<= is also implicitly overloaded.

C# 語言規格C# language specification

如需詳細資訊,請參閱 C# 語言規格位移運算子一節。For more information, see the Shift operators section of the C# language specification.

另請參閱See also