Skip to main content
The bitwise left shift operator (<<) shifts the binary representation of an integer to the left by a specified number of bit positions. It inserts zero bits into the least significant bit (LSB) positions and discards bits shifted beyond the integer’s fixed width.

Syntax

int result = operand << shift_amount;
  • operand: The int value to be shifted.
  • shift_amount: An int specifying the number of positions to shift.
  • Return Value: An int containing the shifted value.

Operational Mechanics

  1. Bit Displacement: Moves every bit in the operand to the left by shift_amount.
  2. Zero Padding: Fills the vacated positions on the right (LSB) with 0.
  3. Arithmetic Equivalent: Mathematically equivalent to multiplying the operand by 2 raised to the power of shift_amount (operand * 2^shift_amount), provided the result does not overflow the platform’s integer limit.

Platform Specifics and Constraints

Dart handles integer width and shift behavior differently depending on the compilation target (Native vs. Web).

Dart Native (VM/AOT)

  • Width: Operations are performed on fixed 64-bit two’s complement integers.
  • Shift Count Handling: The shift amount is not masked. Shifting by 64 or more positions shifts all bits out, resulting in 0.
  • Exceptions: Throws an ArgumentError if shift_amount is negative.
  • Overflow: Bits shifted beyond the 64th position are discarded.

Dart Web

  • Width: Operations map to the JavaScript bitwise left shift. The operand is converted to a signed 32-bit integer before the shift occurs.
  • Shift Count Handling: The effective shift amount is masked to the lower 5 bits (shift_amount & 0x1F). This results in a cyclic shift range of 0 to 31. For example:
    • x << 32 is equivalent to x << 0.
    • x << -1 is equivalent to x << 31 (because -1 in two’s complement has all lower 5 bits set).
  • Exceptions: Does not throw an error for negative shift amounts.
  • Overflow: The result is always truncated to a signed 32-bit integer.

Example

The following example demonstrates shifting the integer 3 left by 2 positions.
void main() {
  int value = 3;              // Binary: 0000 0011
  int shift = 2;

  int result = value << shift; // Binary: 0000 1100

  print('Decimal: $result');           // Output: 12
  print('Binary:  ${result.toRadixString(2).padLeft(8, '0')}'); // Output: 00001100
}
Master Dart with Deep Grasping Methodology!Learn More