<< 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. 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

For the expression x << count, the actual shift count depends on the type of x as follows:

  • If the type of x is int or uint, the shift count is given by the low-order five bits of the second operand. That is, the shift count is computed from count & 0x1F (or count & 0b_1_1111).

  • If the type of x is long or ulong, the shift count is given by the low-order six bits of the second operand. 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. If 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# language specification

For more information, see the Shift operators section of the C# language specification.

See also