<<=(_:_:)
Stores the result of shifting a value’s binary representation the specified number of digits to the left in the left-hand-side variable.
Declaration
static func <<= <RHS>(lhs: inout Self, rhs: RHS) where RHS : BinaryIntegerParameters
- lhs:
The value to shift.
- rhs:
The number of bits to shift
lhsto the left.
Discussion
The << operator performs a smart shift, which defines a result for a shift of any value.
Using a negative value for
rhsperforms a right shift usingabs(rhs).Using a value for
rhsthat is greater than or equal to the bit width oflhsis an overshift, resulting in zero.Using any other value for
rhsperforms a left 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 left by two bits.
var x: UInt8 = 30 // 0b00011110
x <<= 2
// x == 120 // 0b01111000If you use 11 as rhs, x is overshifted such that all of its bits are set to zero.
var y: UInt8 = 30 // 0b00011110
y <<= 11
// y == 0 // 0b00000000Using a negative value as rhs is the same as performing a right shift with abs(rhs).
var a: UInt8 = 30 // 0b00011110
a <<= -3
// a == 3 // 0b00000011
var b: UInt8 = 30 // 0b00011110
b >>= 3
// b == 3 // 0b00000011