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 &<<= (masking bitwise left shift assignment) operator first masks a requested shift amount to ensure it remains within the bit-width limits of the data type, shifts the bit pattern of a mutable integer variable to the left by that masked amount, and then assigns the resulting value back to the original variable.
lhs &<<= rhs

Technical Mechanics

  • lhs (Left-Hand Side): A mutable variable of a type that conforms to the FixedWidthInteger protocol.
  • rhs (Right-Hand Side): The requested number of bit positions to shift.
  • Masking (&): The operator automatically applies a bitmask to the rhs before the shift occurs, constraining the shift amount to the bit width of the lhs.
  • Assignment (=): This is a compound assignment operator; it mutates the lhs in place and evaluates to Void (()).

Masking Calculation

The actual shift amount applied to the lhs is determined by a bitwise AND operation between the rhs and the bit width of the lhs minus one: actual_shift = rhs & (lhs.bitWidth - 1) For example, if lhs is an UInt8 (which has a bit width of 8), the mask applied to the shift amount is 7 (binary 00000111). If you attempt to shift an UInt8 by 10 positions, the operator masks the 10 (00001010) with 7 (00000111), resulting in an actual shift of 2 positions.

Syntax Visualization

var bitPattern: UInt8 = 0b0000_0011 // Decimal 3

// Attempting to shift by 10.
// Masking calculation: 10 & (8 - 1) = 10 & 7 = 2.
// The actual operation performed is a left shift by 2.
bitPattern &<<= 10 

// 0b0000_0011 shifted left by 2 becomes 0b0000_1100 (Decimal 12)
print(bitPattern) // Prints 12

var negativeShiftPattern: UInt8 = 0b0000_0001 // Decimal 1

// Attempting to shift by -1.
// Masking calculation: -1 (11111111 in 8-bit two's complement) & 7 = 7.
// The actual operation performed is a left shift by 7.
negativeShiftPattern &<<= -1

// 0b0000_0001 shifted left by 7 becomes 0b1000_0000 (Decimal 128)
print(negativeShiftPattern) // Prints 128
Note: In Swift, the standard left shift assignment operator (<<=) performs a “smart shift.” If the shift amount is greater than or equal to the type’s bit width, <<= assigns 0 to the variable. Additionally, the standard shift operator triggers a runtime error (trap) if the shift amount is negative. The &<<= operator exists specifically to provide a wrapping masking behavior for the shift amount. This bypasses the zeroing effect when the requested shift exceeds the type’s bit width, and it prevents the negative shift trap by safely masking the two’s complement representation of a negative shift amount into a valid positive shift.
Master Swift with Deep Grasping Methodology!Learn More