Skip to main content
The <<= operator is the bitwise left shift assignment operator in Dart. It shifts the binary representation of the left-hand integer operand to the left by the number of bits specified by the right-hand integer operand, and immediately assigns the resulting value back to the left-hand variable.
variable <<= shiftAmount;
This is a compound assignment operator that serves as syntactic sugar for the following equivalent expression:
variable = variable << shiftAmount;

Technical Mechanics

  • Type Constraints: Both the left-hand variable and the right-hand expression must evaluate to integers (int). Additionally, the right-hand operand (shiftAmount) must be non-negative; attempting to shift by a negative amount throws an ArgumentError.
  • Bit Manipulation: As the bits are shifted to the left, the vacated positions on the right (the least significant bits) are filled with zeroes.
  • Mathematical Equivalence: Shifting an integer left by n bits is mathematically equivalent to multiplying the integer by 2n, provided the operation does not exceed the maximum bit width of the platform’s bitwise integer representation.
  • Overflow and Platform Differences: If the shift operation pushes the set bits (1s) beyond the most significant bit boundary, those bits are discarded, which alters the value and potentially the sign of the integer. This boundary differs based on the compilation target:
    • Native Platforms: Dart integers are 64-bit, and bitwise overflow occurs at the 64-bit boundary.
    • Web Platforms: When compiled to JavaScript, bitwise operations are strictly truncated to 32-bit integers. Even though Dart integers on the web are backed by double-precision floats with a 53-bit safe integer range, overflow for bitwise operations occurs strictly at the 32-bit boundary.

Syntax Visualization

void main() {
  int value = 5; 
  // Binary representation: ... 0000 0101

  value <<= 2;   
  // Shifts bits left by 2.
  // Vacated bits on the right are filled with 0s.
  // Binary becomes:        ... 0001 0100
  
  print(value); // Output: 20 (which is 5 * 2^2)
}
Tired of Poor Dart Skills? Fix That With Deep Grasping!Learn More