Returns the result of shifting a value’s binary representation the specified number of digits to the right.
SDK
- Xcode 9.0+
Framework
- Swift Standard Library
Declaration
static func >> <RHS>(lhs: Int, rhs: RHS) -> Int where RHS : BinaryInteger
Parameters
lhsThe value to shift.
rhsThe number of bits to shift
lhsto the right.
Discussion
The >> operator performs a smart shift, which defines a result for a shift of any value.
Using a negative value for
rhsperforms a left shift usingabs(rhs).Using a value for
rhsthat is greater than or equal to the bit width oflhsis an overshift. An overshift results in-1for a negative value oflhsor0for a nonnegative value.Using any other value for
rhsperforms a right shift onlhsby that amount.
The following example defines x as an instance of UInt8, an 8-bit, unsigned integer type. If you use 2 as the right-hand-side value in an operation on x, the value is shifted right by two bits.
let x: UInt8 = 30 // 0b00011110
let y = x >> 2
// y == 7 // 0b00000111
If you use 11 as rhs, x is overshifted such that all of its bits are set to zero.
let z = x >> 11
// z == 0 // 0b00000000
Using a negative value as rhs is the same as performing a left shift using abs(rhs).
let a = x >> -3
// a == 240 // 0b11110000
let b = x << 3
// b == 240 // 0b11110000
Right shift operations on negative values “fill in” the high bits with ones instead of zeros.
let q: Int8 = -30 // 0b11100010
let r = q >> 2
// r == -8 // 0b11111000
let s = q >> 11
// s == -1 // 0b11111111