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 << (bitwise left shift) operator shifts the binary representation of an integer to the left by a specified number of bit positions. As the bits are shifted left, the high-order (leftmost) bits are discarded, and zero bits are shifted in from the right to fill the vacated low-order positions.
int result = target << shiftAmount;

Operands

  • target: The base int whose bits are being manipulated.
  • shiftAmount: A non-negative int dictating the number of bit positions to shift. If this value is negative, Dart throws an ArgumentError.

Mechanics

Dart integers are 64-bit two’s complement numbers on native platforms. The << operator performs a logical left shift on this 64-bit sequence. Mathematically, evaluating a << b is equivalent to multiplying a by 2b2^b, provided the operation does not result in an overflow beyond the integer limit of the underlying platform.

Syntax Visualization

Positive Integer Shift:
int a = 5;       // 64-bit Binary: 00000000 ... 00000101
int b = a << 3;  // 64-bit Binary: 00000000 ... 00101000

print(b);        // Output: 40 (which is 5 * 2^3)
Negative Integer Shift (Two’s Complement):
int x = -3;      // 64-bit Binary: 11111111 ... 11111101
int y = x << 2;  // 64-bit Binary: 11111111 ... 11110100

print(y);        // Output: -12 (which is -3 * 2^2)

Platform Specifics

Because Dart compiles to both native machine code and JavaScript, the behavior of << diverges based on the compilation target:
  • Dart Native (VM/AOT): Operates on 64-bit two’s complement integers. High-order bits are discarded only when they exceed the 64th bit. Shifting by 32 performs a literal 32-bit shift.
  • Dart Web (JavaScript): JavaScript bitwise operations implicitly convert operands to 32-bit signed integers. This introduces three critical behavioral differences:
    1. Target Truncation: The target is truncated to 32 bits before the shift occurs.
    2. Shift Amount Masking: The shiftAmount is masked to 5 bits (modulo 32). Consequently, shifting by 32 on the web results in a shift of 0 (returning the original number unmodified), whereas native platforms shift by the full 32 positions.
    3. Result Constraint: The final result of the shift is constrained to a 32-bit signed integer. This alters the result even for small targets if the shifted value exceeds 31 bits. For example, 1 << 31 evaluates to 2147483648 on native platforms, but wraps to -2147483648 on the web due to 32-bit signed integer overflow.
Master Dart with Deep Grasping Methodology!Learn More