Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The << operator is the bitwise left shift operator. It shifts the binary representation of its left-hand operand to the left by the number of bit positions specified by its right-hand operand.
result = value << count;

Mechanics

When the left shift operation occurs, the bits of the left operand are moved to the left.
  • High-order bits: Any bits shifted beyond the maximum bit-width of the left operand’s data type are permanently discarded (shifted out).
  • Low-order bits: The vacated bit positions on the right side are always filled with zeros.
uint value = 0b_1100_0000_0000_0000_0000_0000_0000_0011; 
uint result = value << 2;
// result:   0b_0000_0000_0000_0000_0000_0000_0000_1100
// The two high-order 1s are discarded.
// The two low-order positions are zero-filled.

Type Support and Implicit Promotion

The << operator is predefined for the following integral types: int, uint, long, ulong, nint, and nuint. If the left operand is a narrower integral type (byte, sbyte, short, ushort, or char), the C# compiler implicitly promotes it to a 32-bit int before performing the shift. Consequently, the return type of the operation will be an int.
byte a = 0b_0000_0001;
// 'a' is promoted to int. 'result' is of type int.
var result = a << 4; 

Shift Count Masking

To prevent shifting by an amount greater than or equal to the bit-width of the type, C# applies a bitwise AND mask to the right-hand operand (count). The actual number of shifts performed is determined by the type of the left operand:
  • 32-bit operands (int, uint): The shift count is masked with 0x1F (binary 11111). The actual shift count is evaluated as count & 0x1F.
  • 64-bit operands (long, ulong): The shift count is masked with 0x3F (binary 111111). The actual shift count is evaluated as count & 0x3F.
  • Native-sized operands (nint, nuint): The shift count is masked with 0x1F (31) on 32-bit architectures and 0x3F (63) on 64-bit architectures.
Note: Masking with bitwise AND is not equivalent to using the remainder operator (%). In C#, % computes the remainder and preserves the sign of the dividend. For a negative shift count, count % 32 yields a negative result (e.g., -1 % 32 is -1), whereas the bitwise AND mask yields a positive result (-1 & 0x1F is 31).
int value = 1;
int result = value << 33; 
// 33 & 0x1F equals 1. 
// The operation executed is actually (value << 1).

Mathematical Equivalence

In integer arithmetic, shifting a value left by n positions is mathematically equivalent to multiplying that value by 2n2^n, provided that the operation does not result in an overflow where significant high-order bits are discarded.
int x = 5;
int y = x << 3; // Equivalent to 5 * (2^3) = 5 * 8 = 40
Master C# with Deep Grasping Methodology!Learn More