TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
&>> 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
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 to11 % 8(or11 & 7), resulting in an effective shift of3positions.
Shift Behavior by Type
The&>> operator adapts its bit-filling behavior based on whether the lhs type is signed or unsigned:
- 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. - 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 with0; if negative, it fills with1.
Code Visualization
Master Swift with Deep Grasping Methodology!Learn More





