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 in Swift is the bitwise right shift operator. It shifts the binary representation of an integer to the right by a specified number of bit positions, discarding the bits that are shifted beyond the least significant bit (LSB).

Syntax

let result = leftOperand >> rightOperand
  • leftOperand: The integer value whose bits will be shifted.
  • rightOperand: The number of bit positions to shift.

Behavior Based on Integer Type

Swift applies different bit-level mechanics depending on whether the left operand is an unsigned or signed integer type.

Unsigned Integers (Logical Shift)

When applied to an unsigned integer (e.g., UInt8, UInt32), >> performs a logical right shift. The vacated bit positions at the most significant bit (MSB) end are strictly filled with zeros (0).
let unsignedValue: UInt8 = 0b11111111      // Decimal: 255
let shiftedUnsigned = unsignedValue >> 2   // Result: 0b00111111 (Decimal: 63)

Signed Integers (Arithmetic Shift)

When applied to a signed integer (e.g., Int8, Int), >> performs an arithmetic right shift. To preserve the mathematical sign of the integer, the vacated bit positions are filled with the value of the original sign bit (the MSB).
  • If the original value is positive (sign bit is 0), it fills the vacated spaces with 0s.
  • If the original value is negative (sign bit is 1), it fills the vacated spaces with 1s.
// Positive signed integer (Sign bit is 0)
let positiveSigned: Int8 = 0b01111111      // Decimal: 127
let shiftedPositive = positiveSigned >> 2  // Result: 0b00011111 (Decimal: 31)

// Negative signed integer (Sign bit is 1, represented in two's complement)
let negativeSigned: Int8 = -8              // Binary: 0b11111000
let shiftedNegative = negativeSigned >> 2  // Result: 0b11111110 (Decimal: -2)

Operand Constraints

The rightOperand must be greater than or equal to 0 and strictly less than the bit width of the leftOperand. If the right operand falls outside this range, Swift triggers a runtime crash. To safely handle shifts that may exceed the bit width without crashing, Swift provides the masking right shift operator (&>>).
Master Swift with Deep Grasping Methodology!Learn More