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 masking bitwise right shift operator in Swift. It shifts the binary representation of an integer to the right by a specified number of positions, but unlike the standard right shift operator (>>), it prevents runtime traps by masking the shift amount to the bit width of the left-hand operand.

Syntax

let result = lhs &>> rhs
  • lhs (Left-hand side): The integer value whose bits will be shifted.
  • rhs (Right-hand side): The number of bit positions to shift.

Masking Mechanics

In Swift, shifting an integer by a value greater than or equal to its bit width using the standard >> operator results in a runtime overflow error. The &>> operator resolves this by applying a bitmask to the rhs operand before performing the shift. The effective shift amount is calculated as rhs % bitWidth of the lhs type. Because Swift integer bit widths are always powers of 2, this is computed efficiently at the CPU level using a bitwise AND operation: rhs & (bitWidth - 1). For example, if lhs is an 8-bit integer (UInt8), the bit width is 8. If you attempt to shift by 11 positions:
  • Standard >>: Triggers a runtime crash.
  • Masking &>>: The shift amount is masked to 11 % 8 (or 11 & 7), resulting in an effective shift of 3 positions.

Shift Behavior by Type

The &>> operator adapts its bit-filling behavior based on whether the lhs type is signed or unsigned:
  1. Unsigned Integers (Logical Shift): When applied to unsigned types (e.g., UInt8, UInt), &>> performs a logical right shift. The bits are shifted right, and the newly vacated most significant bits (MSBs) on the left are filled with zeros.
  2. Signed Integers (Arithmetic Shift): When applied to signed types (e.g., Int8, Int), &>> performs an arithmetic right shift. To preserve the integer’s two’s complement sign, the vacated MSBs are filled with the value of the original sign bit (sign extension). If the number is positive, it fills with 0; if negative, it fills with 1.

Code Visualization

// --- Masking Behavior 
let value: UInt8 = 0b1000_0000 // 128 in decimal

// 9 % 8 = 1, so this effectively shifts right by 1 position
let maskedShift = value &>> 9  
// Result: 0b0100_0000 (64 in decimal)


// --- Unsigned vs Signed Behavior 

// Unsigned (Logical Shift - Zero Fill)
let unsignedValue: UInt8 = 0b1111_0000 // 240
let unsignedResult = unsignedValue &>> 2
// Result: 0b0011_1100 (60) - Vacated bits filled with 0

// Signed (Arithmetic Shift - Sign Extension)
// 0b1111_0000 in Int8 represents -16 (Two's complement)
let signedValue: Int8 = -16 
let signedResult = signedValue &>> 2
// Result: 0b1111_1100 (-4) - Vacated bits filled with 1 (the sign bit)
Master Swift with Deep Grasping Methodology!Learn More