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 right-shift assignment operator. It shifts the binary representation of its left-hand operand to the right by the number of bits specified by its right-hand operand, and assigns the resulting value back to the left-hand operand.

Syntax

leftOperand >>= rightOperand;
This operation is semantically equivalent to:
leftOperand = leftOperand >> rightOperand;
The primary distinction is that in the compound assignment (>>=), leftOperand is evaluated only once.

Bit-Level Mechanics

The behavior of the right-shift operation depends strictly on the type of the left-hand operand.

1. Arithmetic vs. Logical Shift

  • Signed Types (int, long, sbyte, short): The operator performs an arithmetic shift. The vacated most significant bits (MSBs) are filled with the value of the original sign bit. This preserves the sign of the number (0 for positive, 1 for negative).
  • Unsigned Types (uint, ulong, byte, ushort): The operator performs a logical shift. The vacated MSBs are unconditionally filled with zeros.
// Arithmetic Shift (Signed)
int x = -16;  // Binary: 11111111 11111111 11111111 11110000
x >>= 2;      // Binary: 11111111 11111111 11111111 11111100 (Sign bit 1 is copied)
// x is now -4

// Logical Shift (Unsigned)
uint y = 4294967280; // Binary: 11111111 11111111 11111111 11110000
y >>= 2;             // Binary: 00111111 11111111 11111111 11111100 (Zero-filled)
// y is now 1073741820

2. Shift Count Masking

To prevent shifting by a value greater than or equal to the bit-width of the operand, C# applies a bitwise AND mask to the right-hand operand before executing the shift.
  • 32-bit operands (int, uint): The shift count is masked with 0x1F (binary 11111). The actual shift applied is rightOperand & 0x1F (a value from 0 to 31).
  • 64-bit operands (long, ulong): The shift count is masked with 0x3F (binary 111111). The actual shift applied is rightOperand & 0x3F (a value from 0 to 63).
int z = 1024;
z >>= 33; // 33 & 0x1F = 1. The compiler effectively executes z >>= 1.
// z is now 512

3. Implicit Numeric Promotion and Casting

In C#, bitwise operations are only predefined for 32-bit and 64-bit integers. When applying >>= to smaller integral types (byte, sbyte, short, ushort), the compiler implicitly promotes the left-hand operand to an int to perform the shift. Unlike the standard >> operator, which would require an explicit cast to assign the int result back to the smaller type, the >>= operator automatically performs the underlying explicit narrowing conversion.
byte b = 64;
b >>= 2; 
// Internally evaluated as: b = (byte)(b >> 2);
// b is now 16
Master C# with Deep Grasping Methodology!Learn More